Abdelbari Anouar
Abdelbari Anouar

Reputation: 246

Select & moving Qwidget in the screen

I'm using QTCreator and I created a QWidget, then I have hidden the title bar with setWindowFlags(Qt::CustomizeWindowHint);.

But I can't select or move my widget. How can I use the mouseEvent to solve that?

Upvotes: 7

Views: 8191

Answers (1)

Mat
Mat

Reputation: 206859

If you want to be able to move your window around on your screen by just clicking and dragging (while maintaining the mouse button pressed), here's an easy way to do that:

#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 mousePressEvent, you save the global (screen-coordinate) position of where the mouse was, and then in the mouseMoveEvent, you calculate how far the mouse moved and update the widget's position by that amount.

Note that if you have enabled mouse tracking, you'll need to add more logic to only move the window when a mouse button is actually pressed. (With mouse tracking disabled, which is the default, mouseMoveEvents are only generated when a button is held down).

Upvotes: 22

Related Questions