Qt橡皮筋未被拉

Qt rubberband not being drawn

本文关键字:橡皮筋 Qt      更新时间:2023-10-16

我正在尝试实现橡皮筋。这是我的代码。

void TOTMain::mousePressEvent(QMouseEvent * event)
{
QPoint origin = event->pos();
_selectionSquare = new QRubberBand(QRubberBand::Rectangle, this);
_selectionSquare->setGeometry(QRect(origin, QSize()));
_selectionSquare->raise();
_selectionSquare->show();
}
void TOTMain::mouseMoveEvent(QMouseEvent *event)
{
QPoint origin = event->pos();
_selectionSquare->setGeometry(QRect(origin, event->pos()).normalized());
}
void TOTMain::mouseReleaseEvent(QMouseEvent *event)
{
_selectionSquare->hide();
// determine selection, for example using QRect::intersects()
// and QRect::contains().
}

问题是乐队没有被绘制。我确认它正在构建并通过拖动持续存在,但没有渲染。

任何想法都值得赞赏。

看看你的mouseMoveEvent实现...

void TOTMain::mouseMoveEvent(QMouseEvent *event)
{
QPoint origin = event->pos();
_selectionSquare->setGeometry(QRect(origin, event->pos()).normalized());
}

您将橡皮筋的几何图形设置为QRect(origin, event->pos()),但您之前已设置origin = event->pos()因此矩形的左上角和右下角相同。

使origin成为类的成员变量变量(未经测试)...

class TOTMain: public QWidget {
public:
protected:
virtual void mousePressEvent (QMouseEvent *event) override
{
_origin = event->pos();
_selectionSquare = new QRubberBand(QRubberBand::Rectangle, this);
_selectionSquare->setGeometry(QRect(_origin, QSize()));
_selectionSquare->raise();
_selectionSquare->setStyleSheet("{ background-color : red; }");
_selectionSquare->show();
}
virtual void mouseMoveEvent (QMouseEvent *event) override
{
_selectionSquare->setGeometry(QRect(_origin, event->pos()).normalized());
}
virtual void mouseReleaseEvent (QMouseEvent *event) override
{
_selectionSquare->hide();
// determine selection, for example using QRect::intersects()
// and QRect::contains().
}
private:
QPoint       _origin;
QRubberBand *_selectionSquare = nullptr;
};