qt拖拽事件重写

1.qt中的拖拽事件步骤

1设置接受拖拽

2重写事件就可以了

3其他的控件如何要可以套模板

2.例子

c 复制代码
#include <QGroupBox>
#include <QObject>
#include <QDragEnterEvent>
#include <QFileInfo>
#include <QMimeData>

//重写,指出拖拽指定的文件进来,可以自己命名什么文件可以拖进来

class DGroupBox : public QGroupBox
{
    Q_OBJECT
public:
    DGroupBox(){
        setAcceptDrops(true);
    }
    
protected:
    void dragEnterEvent(QDragEnterEvent *event) override
    {
        QList<QUrl> urls = event->mimeData()->urls();
        bool acceptDrop = false;
        for (const QUrl &url : urls) {
            QString filePath = url.toLocalFile();
            //if (filePath.endsWith(".txt", Qt::CaseInsensitive))
            if(QFileInfo(filePath).fileName() == m_acceptFileName)
            {
                acceptDrop = true;
                event->setDropAction(Qt::CopyAction);
                event->accept();
                break;
            }
        }
        if (!acceptDrop) {
            event->setDropAction(Qt::IgnoreAction);
            event->ignore();
        }
    }
    
    void dragMoveEvent(QDragMoveEvent *event) override
    {
        switch (event->dropAction()) {
        case Qt::CopyAction:
            event->accept();
            setCursor(Qt::CursorShape::DragCopyCursor);
            break;
        default:
            event->ignore();
            setCursor(Qt::ForbiddenCursor);
            break;
        }
    }
    
    void dropEvent(QDropEvent *event) override
    {
        QList<QUrl> urls = event->mimeData()->urls();
        if (!urls.isEmpty()) {
            for (const QUrl &url : urls) {
                QString filePath = url.toLocalFile();
                //if (filePath.endsWith(".txt", Qt::CaseInsensitive))
                if(QFileInfo(filePath).fileName() == m_acceptFileName)
                {
                    // 将文件路径设置为QLabel的文本
                    emit accpetFile(filePath);
                }
            }
        }
        event->acceptProposedAction();
    }
signals:
    void accpetFile(QString filePath);
    
public:
    void setAcceptFileName(QString name){m_acceptFileName = name;}
private:
    QString m_acceptFileName = "encrypted_data.dat";
    
};

#endif // DGROUPBOX_H
相关推荐
用户805533698033 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
xcyxiner3 天前
DicomViewer (vcpkg Windows和ubuntu编译)7
qt
Quz8 天前
QML Hello World 入门示例
qt
xcyxiner11 天前
DicomViewer (dcmtk读取dcm文件)5
qt
xcyxiner12 天前
DicomViewer (后台线程处理文件)4
qt
xcyxiner12 天前
DicomViewer (添加模型类)3
qt
xcyxiner13 天前
DicomViewer (目录调整) 2
qt
xcyxiner13 天前
dcmtk vtk vtk-dicom(gdcm) 编译(debug) v2
qt
桥田智能15 天前
桥田智能 QT-650S:面向白车身焊装的 800kg 重载快换解决方案
开发语言·qt·系统架构
森G15 天前
75、服务器源码解析---------云视频服务项目
linux·服务器·网络·c++·qt