天天看点

Qt拖拽的小Demo

效果图:

Qt拖拽的小Demo

思路如下:

1、在构造函数中设置拖拽可用,setAcceptDrops(true);

2、在拖的时候获取信息,拽的时候做处理(处理时已去除重复文件):

void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{
    if(event->mimeData()->hasFormat("text/uri-list")) {
        event->acceptProposedAction();
    }
    qDebug() << "drag enter";
}

void MainWindow::dropEvent(QDropEvent *event)
{
    QList<QUrl> urls = event->mimeData()->urls();
    if(urls.isEmpty()) {
        return;
    }
    foreach(QUrl url, urls) {
        QString file_all_name = url.toLocalFile();
        if(!m_fileList.contains(file_all_name)) {
            m_fileList << file_all_name;
            QString fileName = file_all_name.split("/").last();
            int w = 300;
            int h = 100;
            QPushButton *btn = new QPushButton(this);
            btn->resize(w,h);
            btn->move((1-m_fileList.count()%2)*w, (m_fileList.count() - 1)/2*h + ui->label->height());
            btn->setText(fileName);
            btn->setStyleSheet("background-color: rgb(170, 255, 255);");
            connect(btn, &QPushButton::clicked, [=](){
                for(int i = 0; i < m_fileList.count(); i++) {
                    QString tmp = m_fileList.at(i);
                    if(tmp.split("/").last() == btn->text()) {
                        ui->label->setText(tmp);
                    }
                }
            });
            btn->show();
        }
    }
}      

3、还可以做的小优化:

继续阅读