[英]Using Qt, how do I resize a widget using the mouse move event going up or to the left
I have a QMainWindow
that has a QWidget
. 我有一个有QWidget
的QMainWindow
。 The QWidget
appears, and has its origin set in the mouse down event of the QMainWindow
. 出现QWidget
,其原点设置在QMainWindow
的鼠标按下事件中。 Then, in the mouse move event of the QMainWindow
, the geometry of the QWidget
is set, such that it appears that the user is drawing a rectangle on top of the QMainWindow
. 然后,在QMainWindow
的鼠标移动事件中,设置QWidget
的几何图形,使得用户在QMainWindow
顶部绘制一个矩形。 This is how I'm doing it: 这就是我这样做的方式:
void MyQMainWindow::mousePressEvent(QMouseEvent * E) {
QPoint pos = e->pos();
myQWidget->setGeometry(pos.x(), pos.y(), 0, 0);
myQWidget->show();
}
void MyQMainWindow::mouseMoveEvent(QMouseEvent * e) {
QPoint pos = e->pos();
QPoint prv = myQWidget->pos();
int w = pos.x() - prv.x();
int h = pos.y() - prv.y();
myQWidget.setGeometry(prv.x(), prv.y(), w, h);
}
void MyQMainWindow::mouseReleaseEvent(QMouseEvent *) {
myQWidget.hide();
}
The problem with this approach is that when I drag the mouse up, or left of where I clicked. 这种方法的问题是当我向上拖动鼠标时,或者在我单击的位置左侧。 My calculations for w
and h
are negative, and so the window does not resize correctly (or at all). 我对w
和h
计算是否定的,因此窗口没有正确调整大小(或根本不调整大小)。
I realize that moving up/left would mean that I need to change the origin of the widget, while keeping the bottom right corner of it in the same place by also increasing the width/height as needed, but how do I do this? 我意识到向上/向左移动意味着我需要更改小部件的原点,同时通过根据需要增加宽度/高度来保持小部件的右下角,但是我该怎么做?
Thanks! 谢谢!
I would do something like this: 我会做这样的事情:
void MyQMainWindow::updateWidgetGeometry()
{
if (_initial == QPoint(-1,-1)) {
return;
}
x = qMin(_initial.x(), _current.x());
y = qMin(_initial.y(), _current.y());
w = abs(_initial.x() - _current.x());
h = abs(_initial.y() - _current.y());
myQWidget.setGeometry(x, y, w, h);
}
void MyQMainWindow::mousePressEvent(QMouseEvent * E)
{
_initial = e->pos();
_current = e->pos();
updateWidgetGeometry()
myQWidget->show();
}
void MyQMainWindow::mouseMoveEvent(QMouseEvent * E)
{
_current= e->pos();
updateWidgetGeometry()
}
void MyQMainWindow::mouseReleaseEvent(QMouseEvent *)
{
_current = QPoint(-1,-1);
_initial = QPoint(-1,-1);
myQWidget.hide();
}
Typed this up without a compiler. 在没有编译器的情况下输入它。
By the way, you might also need to setMouseTracking(true) so that if your mouse move event happens inside the widget your MyQMainWindow gets to handle it. 顺便说一下,你可能还需要setMouseTracking(true),这样如果你的鼠标移动事件发生在你的MyQMainWindow处理它的小部件内。 I'm not sure about that bit. 我不确定那一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.