Qt拖拽功能
窗口拖拽文件读取文件路径+文件名
void MainWindow::dragEnterEvent(QDragEnterEvent *ev)
{
if(ev->mimeData()->hasUrls())
{
ev->accept();//接收拖动进入事件
}
//ev->ignore();//若忽略该事件,则不会发生之后的事件,拖放到此结束
}
void MainWindow::dropEvent(QDropEvent *ev)
{
QList<QUrl> urls = ev->mimeData()->urls();
ui->lineEdit_source->setText(urls[0].toLocalFile());
ui->lineEdit_target->setText(urls[0].toLocalFile());
//if(ev->mimeData()->hasUrls())
//{
//QList<QUrl> urls = ev->mimeData()->urls();
// ui->lineEdit_source->text() = urls.at(0).toLocalFile();
// ui->lineEdit_target->text() = urls.at(1).toLocalFile();
//for(int i=0; i<urls.size(); i++)
//{
//}
//}
}
调试过程信号槽函数
ui->label->setAcceptDrops(true);
拖拽到指定控件获得路径+文件名
https://www.pianshen.com/article/872738975/
bool eventFilter(QObject *watched, QEvent *event);
//drag file
ui->pushButton->installEventFilter(this);
ui->pushButton->setAcceptDrops(true);
ui->pushButton_2->installEventFilter(this);
ui->pushButton_2->setAcceptDrops(true);
bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
if (watched == ui->pushButton)
{
if (event->type() == QEvent::DragEnter) {
// [[2]]: 当拖放时鼠标进入label时, label接受拖放的动作
QDragEnterEvent *dee = dynamic_cast<QDragEnterEvent *>(event);
dee->acceptProposedAction();
return true;
} else if (event->type() == QEvent::Drop)
{
QDropEvent *de = dynamic_cast<QDropEvent *>(event);
QList<QUrl> urls = de->mimeData()->urls();
if (urls.isEmpty()) { return true; }
ui->lineEdit_source->setText( urls.first().toLocalFile());;
}
} else if (watched == ui->pushButton_2)
{
if (event->type() == QEvent::DragEnter)
{
// [[2]]: 当拖放时鼠标进入label时, label接受拖放的动作
QDragEnterEvent *dee = dynamic_cast<QDragEnterEvent *>(event);
dee->acceptProposedAction();
return true;
} else if (event->type() == QEvent::Drop)
{
// [[3]]: 当放操作发生后, 取得拖放的数据
QDropEvent *de = dynamic_cast<QDropEvent *>(event);
QList<QUrl> urls = de->mimeData()->urls();
if (urls.isEmpty()) { return true; }
ui->lineEdit_target->setText( urls.first().toLocalFile());
}
}
return QMainWindow::eventFilter(watched, event);
}
标签:功能,Qt,拖拽,ui,urls,ev,true,event,拖放
From: https://www.cnblogs.com/timapi/p/17441408.html