绘制折线时未调用虚拟 paint()

Virtual paint() is not getting called while drawing Polyline

我是 Qt 的新手,想编写代码来更改 Qt 的默认选择行为。所以我试图覆盖虚拟绘画方法。但是没有调用 paint 方法。
在代码下方,只需打印折线,然后 paint() 会尝试更改其选择行为。

polyline.h

class Polyline : public QGraphicsPathItem
{
public:
    Polyline();
    virtual void paint (QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override
    {
        auto copied_option = *option;
        copied_option.state &= ~QStyle::State_Selected;
        auto selected = option->state & QStyle::State_Selected;
        QGraphicsPathItem::paint(painter, &copied_option, widget);
        if (selected)
        {
            painter->save();
            painter->setBrush(Qt::red);
            painter->setPen(QPen(option->palette.windowText(), 5, Qt::DotLine));
            painter->drawPath(shape());
            painter->restore();
        }
    }
    QGraphicsPathItem* drawPolyline();
};      
   

polyline.cpp

#include "polyline.h"

Polyline::Polyline()
{}

QGraphicsPathItem* Polyline::drawPolyline()
{
    QPolygonF polygon;
    polygon<< QPointF (150,450) << QPointF (350,450) <<QPointF (350,200) << QPointF (250,100)<<QPointF (150,200);

    QPainterPath pPath;

    pPath.addPolygon(polygon);
    QGraphicsPathItem* new_item = new QGraphicsPathItem(pPath);
    new_item->setPen(QPen(QColor("red"), 5));
    new_item->setPath(pPath);
    new_item->setFlags(QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsMovable);
    return new_item;
}

   

main.cpp

#include "polyline.h"
#include <QGraphicsScene>
#include <QGraphicsView>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QGraphicsView view;
    QGraphicsScene scene;
    view.setScene(&scene);

    Polyline p;
    QGraphicsPathItem* poly = p.drawPolyline();
    scene.addItem(poly);
    view.show();
    return a.exec();
}

 

我哪里错了?

问题是您没有创建任何 Polyline 对象并将其附加到 window 或小部件。

因此没有 Polyline 对象可以调用 paint 函数。

一个简单的解决方案是让您的 drawPolyline 函数创建一个 Polyline 对象而不是您现在创建的 QGraphicsPathItem 对象:

QGraphicsPathItem* new_item = new Polyline(pPath);

记得修改Polyline构造函数取路径,转发给基QGraphicsPathItem class.


另一个改进是认识到 drawPolyline 根本不需要成为成员函数。而且它的名字很糟糕。我建议您将其定义为 source-file 局部函数,改名为 createPolyline

namespace
{
    QGraphicsPathItem* createPolyline()
    {
        // The body of your `drawPolyline` function
        // With the fix mentioned above
        // ...
    }
}

那就改用这个函数:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QGraphicsView view;
    QGraphicsScene scene;
    view.setScene(&scene);

    scene.addItem(createPolyline());
    view.show();
    return a.exec();
}