Qt的拖拽操作例子
本文是一个拖拽文本的例子。演示了如何把按钮的标题拖拽到文本编辑框里。Qt对拖拽的封装很好,QDrag对象简单易用。本文程序测试环境是VS2017和Qt5.9。下面是程序拖拽时的效果图,可以看出来拖拽的时候光标下方也显示了文本内容:
头文件。本功能是在主窗口中实现的。下面代码里QtTest就是主窗口类,ui.pbFlash是按钮控件:
class QtTest : public QMainWindow { Q_OBJECT public: QtTest(QWidget *parent = Q_NULLPTR); ~QtTest(); private: bool eventFilter(QObject* src, QEvent* event) override; QPixmap createDragPixmap(const QString& text); private: Ui::QtTestClass ui; QPoint pressPt; };
CPP文件:
QtTest::QtTest(QWidget *parent) : QMainWindow(parent) { ui.setupUi(this); ui.pbFlash->installEventFilter(this); } bool QtTest::eventFilter(QObject* src, QEvent* event) { if (event->type() == QEvent::MouseButtonPress) { QMouseEvent *mouseEvent = dynamic_cast<QMouseEvent*>(event); if (mouseEvent->buttons() & Qt::LeftButton) { pressPt = mouseEvent->pos(); } } if (event->type() == QEvent::MouseMove) { QMouseEvent *mouseEvent = dynamic_cast<QMouseEvent*>(event); if ((mouseEvent->buttons() & Qt::LeftButton) && (mouseEvent->pos() - pressPt).manhattanLength() > QApplication::startDragDistance()) { QDrag drag(ui.pbFlash); QMimeData* data = new QMimeData; data->setText(ui.pbFlash->text()); drag.setMimeData(data); drag.setPixmap(createDragPixmap(ui.pbFlash->text())); drag.setHotSpot(QPoint(-10, -10)); /* 指的是setPixmap(...)的热点 */ drag.exec(); } } return false; } QPixmap QtTest::createDragPixmap(const QString& text) { QFontMetrics fm = fontMetrics(); QSize tsz = fm.size(0, text); QPixmap pixmap(tsz); pixmap.fill(Qt::transparent); QPainter painter(&pixmap); painter.setOpacity(0.5); painter.drawText(QRect(QPoint(0, 0), tsz), 0, text); return pixmap; } QtTest::~QtTest() { }
上面代码中使用了事件过滤器拦截按钮的消息以达到启动拖拽的目的。