赞
踩
设置窗口 flag:
this->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
创建变量存储位置
QPoint m_dragPosition;
对鼠标左键按下和移动事件做处理
- void DraggableDialog::mousePressEvent(QMouseEvent *event) {
- isDragging = true;
- dragPos = event->globalPos() - frameGeometry().topLeft();
- }
-
- // 鼠标移动事件,实现拖动
- void DraggableDialog::mouseMoveEvent(QMouseEvent *event) {
- if (isDragging) {
- move(event->globalPos() - dragPos);
- }
- }
-
- // 鼠标释放事件,结束拖动
- void DraggableDialog::mouseReleaseEvent(QMouseEvent *event) {
- isDragging = false;
- }
- #ifndef DRAGGABLEDIALOG_H
- #define DRAGGABLEDIALOG_H
-
- #include <QDialog>
- #include <QMouseEvent>
- namespace Ui {
- class DraggableDialog;
- }
-
- class DraggableDialog : public QDialog
- {
- Q_OBJECT
-
- public:
- explicit DraggableDialog(QWidget *parent = nullptr);
- ~DraggableDialog();
-
- protected:
- // 鼠标按下事件,记录点击位置
- void mousePressEvent(QMouseEvent *event) override;
-
- // 鼠标移动事件,实现拖动
- void mouseMoveEvent(QMouseEvent *event) override;
-
- // 鼠标释放事件,结束拖动
- void mouseReleaseEvent(QMouseEvent *event) override ;
-
- private:
- bool isDragging;
- QPoint dragPos;
-
- private:
- Ui::DraggableDialog *ui;
- };
-
- #endif // DRAGGABLEDIALOG_H
cpp
- #include "draggabledialog.h"
- #include "ui_draggabledialog.h"
-
- DraggableDialog::DraggableDialog(QWidget *parent) :
- QDialog(parent),
- ui(new Ui::DraggableDialog)
- {
- ui->setupUi(this);
- // 设置窗口无边框
- this->setWindowFlags(Qt::FramelessWindowHint);
- setToolTip("窗口无边框,可拖动");
- }
-
- DraggableDialog::~DraggableDialog()
- {
- delete ui;
- }
- void DraggableDialog::mousePressEvent(QMouseEvent *event) {
- isDragging = true;
- dragPos = event->globalPos() - frameGeometry().topLeft();
- }
-
- // 鼠标移动事件,实现拖动
- void DraggableDialog::mouseMoveEvent(QMouseEvent *event) {
- if (isDragging) {
- move(event->globalPos() - dragPos);
- }
- }
-
- // 鼠标释放事件,结束拖动
- void DraggableDialog::mouseReleaseEvent(QMouseEvent *event) {
- isDragging = false;
- }
main
- int main(int argc, char *argv[]) {
- QApplication app(argc, argv);
-
- DraggableDialog dialog;
- dialog.show();
-
- return app.exec();
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。