当前位置:网站首页>QT学习:QDropEvent拖拽事件
QT学习:QDropEvent拖拽事件
2022-07-29 05:07:00 【上官宏竹】
使用QT实现一个如下的拖拽、拖放动作,只需要三步。主要是使用dropEvent和dragEnterEvent事件处理即可以。
步骤
- 1、
setAcceptDrops(true)设置目的QWidget接收拖拽拖放事件 - 2、重写
dragEnterEvent事件,并对正确的事件进行acceptProposedAction接受操作 - 3、重写
dropEvent事件,处理主要的逻辑即可
实现
在UI中画好布局,然后全部代码如下所示:
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
setAcceptDrops(true); // 1. 整个MainWindow接收拖拽事件
}
// 2.重写拖拽进入事件
void MainWindow::dragEnterEvent(QDragEnterEvent* event)
{
if (event->mimeData()->hasUrls()) {
event->acceptProposedAction(); // 3. 有拖拽文件时设置接受
}
}
// 4.重写件拖拽放下事件,处理所需
void MainWindow::dropEvent(QDropEvent *event)
{
if (event->mimeData()->hasUrls()) {
QList<QUrl> urls = event->mimeData()->urls();
if(urls.isEmpty()) {
return;
}
ui->textEdit->setText(urls.first().toLocalFile());
}
}
在dragEnterEvent中判断如果当前mime类型为文本或者url(本地文件是以url类型描述的),则调用acceptProposedAction来设置对应的事件发生flag——只有设置了这个flag,后面的drop事件才会发生。如果要捕获所有类型的拖放事件则可以直接调用acceptProposedAction。
边栏推荐
- Quick start JDBC
- Northeast University Data Science Foundation (matlab) - Notes
- SM整合原来这么简单,步骤清晰(详细)
- Open the tutorial of adding and modifying automatically playing music on the open zone website
- ODOO开发教程之图表
- Pytorch learning notes
- scikit-learn——机器学习应用开发的步骤和理解
- Mysql的自连接和联合查询
- What if excel is stuck and not saved? The solution of Excel not saved but stuck
- How does WPS take quick screenshots? WPS quick screenshot method
猜你喜欢
随机推荐
传奇如何一台服务器配置多个版本微端更新
SparkSql批量插入或更新,保存数据到Mysql中
Quick start JDBC
SM integration is as simple as before, and the steps are clear (detailed)
How to set row height and column width in excel? The method of setting row height and column width in Excel
Arfoundation starts from scratch 3- create an arfoundation project
开区网站打开自动播放音乐的添加跟修改教程
搭建手机APP需要用到什么服务器
AUTOSAR from introduction to proficiency 100 lectures (78) -autosar-dem module
[file download] easyexcel quick start
学习数据库的第一个程序
三层项目的架构分析及构造方法的参数名称注入
TCP three handshakes and four waves
Office提示系统配置无法运行怎么办?
What if the computer cannot open excel? The solution of Excel not opening
ARFoundation入门教程10-平面检测和放置
Legend how to configure multiple versions of wechat updates on one server
【微信小程序--解决display:flex最后一行对齐问题。(不连续排列会分到两边)】
ODOO开发教程之图表
[config] configure array parameters









