1. 程式人生 > >Qt實現視窗整體拖拽功能.

Qt實現視窗整體拖拽功能.

我們都知道,當我們滑鼠點選並移動應用程式的上邊框時,窗口才會整體移動,但有些視窗,你點選移動其他部分,也可以讓視窗跟著滑鼠移動,這裡就教你如何整體移動視窗.

其實實現這樣的功能很簡單,只需要重寫以下的3個滑鼠函式即可.

//"c.h"
#ifndef C_H
#define C_H

#include <QtWidgets/QWidget>
#include "ui_c.h"
#include <QMouseEvent>

class c : public QWidget
{
    Q_OBJECT

public:
    c(QWidget *parent = 0
); ~c(); protected: void mousePressEvent(QMouseEvent *event); void mouseMoveEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); private: Ui::cClass ui; bool m_move; QPoint m_startPoint; QPoint m_windowPoint; }; #endif // C_H
//"c.cpp"
#include "c.h"
c::c(QWidget *parent) : QWidget(parent) { ui.setupUi(this); //給是否移動的標誌初始化為false. m_move = false; } c::~c() { } void c::mousePressEvent(QMouseEvent *event) { //當滑鼠左鍵點選時. if (event->button() == Qt::LeftButton) { m_move = true; //記錄滑鼠的世界座標. m_startPoint = event
->globalPos(); //記錄窗體的世界座標. m_windowPoint = this->frameGeometry().topLeft(); } } void c::mouseMoveEvent(QMouseEvent *event) { if (event->buttons() & Qt::LeftButton) { //移動中的滑鼠位置相對於初始位置的相對位置. QPoint relativePos = event->globalPos() - m_startPoint; //然後移動窗體即可. this->move(m_windowPoint + relativePos ); } } void c::mouseReleaseEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { //改變移動狀態. m_move = false; } }