Selecting and moving a Qwidget on the screen

I use QTCreator and I created a QWidget, then I hid the title bar with setWindowFlags(Qt::CustomizeWindowHint);.

But I can not select or move my widget. How can I use mouseEvent to solve this problem?

+5
source share
1 answer

If you want you to be able to move your window on the screen by simply clicking and dragging (while keeping the mouse button pressed), here is an easy way to do this:

#include <QtGui>

class W: public QWidget
{
    Q_OBJECT

    public:
        explicit W(QWidget *parent=0) : QWidget(parent) { }

    protected:
        void mousePressEvent(QMouseEvent *evt)
        {
            oldPos = evt->globalPos();
        }

        void mouseMoveEvent(QMouseEvent *evt)
        {
            const QPoint delta = evt->globalPos() - oldPos;
            move(x()+delta.x(), y()+delta.y());
            oldPos = evt->globalPos();
        }

    private:
        QPoint oldPos;
};

In mousePressEventyou save the global (screen coordinate) position where the mouse was located, and then in mouseMoveEventyou calculate how far the mouse moved and updated the position of the widgets by this amount.

, , , . ( , , mouseMoveEvent ).

+18

All Articles