【问题标题】:QT Draw Rectangle on QGraphicsitemQT在QGraphicsitem上绘制矩形
【发布时间】:2017-07-07 13:56:15
【问题描述】:

我的工作环境: Qt 5.8 MSVC2015 64bit, QT GraphicsView, QGraphicsObject, Windows 7 64 bit。

在我的应用程序中,我将多个 QGraphicsitem 添加到单个图形场景和单个图形视图中。

但我需要根据鼠标位置在 QGraphicsitem 图像顶部绘制空的绿色矩形。 所以我尝试了以下方法:

QRubberBand* _rubberBand = new QRubberBand(QRubberBand::Rectangle, this);
_rubberBand->setGeometry(QRect(MousePos.x() -2, MousePos.y() - 2, MousePos.x() + 2, MousePos.y() + 2).normalized());
_rubberBand->setAutoFillBackground(false);
QPalette pal;
pal.setBrush(QPalette::Highlight, QBrush(Qt::green));
_rubberBand->setPalette(pal);
_rubberBand->show();

QRubberBand 的问题,它会动态改变大小,我想绘制小矩形,而不是闪烁的 RubberBand。

QRubberBand 输出:

预期输出:

【问题讨论】:

  • stackoverflow.com/questions/44395296/… 的可能重复项。请注意,问题本身已经包含了很大一部分可能的解决方案。
  • @m7913d ,QPalette 没有 setColor 选项。 //pal.setColor();
  • QPalette 有一个setColor 方法,但您还应该指定一个ColorRole。请注意,重复的问题不使用QPalette,尽管也有可能。
  • @m7913d,不,我试过 pal.setColor(QPalette::Highlight, QColor(128,128,255));但它仍然用颜色填充整个矩形。我只需要用颜色设置边框。
  • 您可能需要将画笔设置为透明。不过,您创建的答案是一个很好的解决方案。

标签: c++ qt


【解决方案1】:

@m7913d,非常感谢您的增值建议。 我有 Override QRubberBand 类并设置 QRubberBand 类 setGeometry、setPen 和它的颜色。

这是最终解决方案代码:

class roiFrame : public QRubberBand
{
public:
    roiFrame(Shape s, QWidget * p = 0):QRubberBand(s, p){}
    ~roiFrame(){}
protected:
    void paintEvent(QPaintEvent *pe)
    {
        Q_UNUSED(pe);
        QStyleOptionRubberBand opt;
        QStylePainter painter(this);
        opt.initFrom(this);
        QRect rectangle(0,0,30, 15);
        QColor color(Qt::green);
        painter.setPen(color);
        painter.drawRect(rectangle);
    }
};

来电代码:

_rectFrame = new roiFrame(QRubberBand::Rectangle, this);
_rectFrame->setGeometry(QRect(thumbMousePos.x() -1, thumbMousePos.y() - 1, thumbMousePos.x() + 1, thumbMousePos.y() + 1).normalized());
_rectFrame->setAutoFillBackground(false);
_rectFrame->show();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    • 2011-12-05
    • 2018-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多