选择&在屏幕上移动Qwidget [英] Select & moving Qwidget in the screen
问题描述
我使用QTCreator,我创建了一个QWidget,然后我已隐藏标题栏与 setWindowFlags(Qt :: CustomizeWindowHint);
。
I'm using QTCreator and I created a QWidget, then I have hidden the title bar with setWindowFlags(Qt::CustomizeWindowHint);
.
但我不能选择或移动我的小部件。我如何使用mouseEvent来解决这个问题?
But I can't select or move my widget. How can I use the mouseEvent to solve that?
推荐答案
如果您希望能够通过点击和拖动在屏幕上移动窗口(同时保持鼠标按钮按下),这里有一个简单的方法:
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;
};
在 mousePressEvent
中,屏幕坐标)位置,然后在 mouseMoveEvent
中,计算鼠标移动的距离以及将窗口小部件的位置更新该量。
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.
请注意,如果您启用了鼠标跟踪,则需要添加更多逻辑,以便在实际按下鼠标按钮时移动窗口。 (默认情况下禁用鼠标跟踪, 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, mouseMoveEvent
s are only generated when a button is held down).
这篇关于选择&在屏幕上移动Qwidget的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!