Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 690
Abdelbari Anouar Avatar asked Jul 03 '12 15:07

Abdelbari Anouar


1 Answers

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).

like image 169
Mat Avatar answered Oct 04 '22 12:10

Mat