QT 界面隐藏标题栏后设置可支持拖动,需要重写界面的mousePressEvent,mouseMoveEvent,mouseReleaseEvent事件,代码如下。
1 #include <QWidget> 2 #include <QMouseEvent> 3 4 class CustomWidget : public QWidget { 5 Q_OBJECT 6 7 public: 8 explicit CustomWidget(QWidget *parent = nullptr); 9 10 protected: 11 void mousePressEvent(QMouseEvent *event) override; 12 void mouseMoveEvent(QMouseEvent *event) override; 13 void mouseReleaseEvent(QMouseEvent *event) override; 14 15 private: 16 bool isDragging; 17 QPoint dragPosition; 18 }; 19 20 CustomWidget::CustomWidget(QWidget *parent) : QWidget(parent), isDragging(false) { 21 // 隐藏标题栏 22 setWindowFlags(Qt::FramelessWindowHint); 23 } 24 25 void CustomWidget::mousePressEvent(QMouseEvent *event) { 26 if (event->button() == Qt::LeftButton) { 27 isDragging = true; 28 dragPosition = event->globalPos() - frameGeometry().topLeft(); 29 event->accept(); 30 } 31 } 32 33 void CustomWidget::mouseMoveEvent(QMouseEvent *event) { 34 if (isDragging) { 35 move(event->globalPos() - dragPosition); 36 event->accept(); 37 } 38 } 39 40 void CustomWidget::mouseReleaseEvent(QMouseEvent *event) { 41 if (event->button() == Qt::LeftButton) { 42 isDragging = false; 43 event->accept(); 44 } 45 } 46 47 int main(int argc, char *argv[]) { 48 QApplication a(argc, argv); 49 CustomWidget widget; 50 widget.setGeometry(100, 100, 400, 200); // 设置初始位置和大小 51 widget.show(); 52 53 return a.exec(); 54 }
标签:QT,拖动,void,标题栏,QMouseEvent,isDragging,CustomWidget,event From: https://www.cnblogs.com/jiaxinyoudiansha/p/17763386.html