当前位置:网站首页>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
。
边栏推荐
- Button for QT custom switch effect
- How does excel filter out the content you want? Excel table filtering content tutorial
- WPS insert hyperlink cannot be opened. What should I do if I prompt "unable to open the specified file"!
- JS daily question (12)
- js(forEach)出现return无法结束函数的解决方法
- 缓存穿透、缓存击穿、缓存雪崩以及解决方法
- 2021-10-11
- ARFoundation从零开始5-AR图像跟踪
- Google GTEST event mechanism
- Getting started with solidity
猜你喜欢
Word如何查看文档修改痕迹?Word查看文档修改痕迹的方法
js(forEach)出现return无法结束函数的解决方法
How does word view document modification traces? How word views document modification traces
Young freshmen yearn for more open source | here comes the escape guide from open source to employment!
Google gtest事件机制
The person who goes to and from work on time and never wants to work overtime has been promoted in front of me
Soft link & hard link
ARFoundation从零开始9-AR锚点(AR Anchor)
Create a mindscore environment in modelars, install mindvision, and conduct in-depth learning and training (Huawei)
Getting started with solidity
随机推荐
【微信小程序--解决display:flex最后一行对齐问题。(不连续排列会分到两边)】
JS daily question (10)
What if excel is stuck and not saved? The solution of Excel not saved but stuck
关于thymeleaf的配置与使用
Deep learning brush a bunch of tricks of SOTA
Solution | get the relevant information about the current employees' highest salary in each department |
TCP三次握手四次挥手
Wechat picture identification
【文件下载】Easyexcel快速上手
ARFoundation从零开始5-AR图像跟踪
Original code, inverse code, complement code
JS daily question (11)
2022年泰迪杯数据挖掘挑战赛C题方案及赛后总结
学习数据库的第一个程序
SQL log
Quick start JDBC
MySQL many to many relationship, grouping and splicing to query multiple data to one data
Diagram of odoo development tutorial
DataSourceClosedException: dataSource already closed at Mon Oct 25 16:55:48 CST 2021
Use annotation test in idea