7

我正在使用 QTCreator 并创建了一个 QWidget,然后我用 setWindowFlags(Qt::CustomizeWindowHint);.

但我无法选择或移动我的小部件。如何使用 mouseEvent 来解决这个问题?

4

1 回答 1

22

如果您希望能够通过单击和拖动(同时按住鼠标按钮)在屏幕上移动窗口,这是一种简单的方法:

#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;
};

mousePressEvent中,您保存鼠标所在位置的全局(屏幕坐标)位置,然后在 中mouseMoveEvent,您计算​​鼠标移动的距离并按该数量更新小部件的位置。

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

于 2012-07-03T15:53:19.313 回答