我是Qt新手,我想编写代码来改变Qt的默认选择行为。因此,我试图覆盖虚拟油漆方法。但是油漆方法没有被调用。
在下面的代码中,只需打印polyline,并尝试改变它的选择行为。
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();
}我哪里错了?
发布于 2022-02-11 14:02:55
问题是,您没有创建任何Polyline对象并将其附加到窗口或小部件。
因此,没有可以调用Polyline函数的paint对象。
一个简单的解决方案是让您的drawPolyline函数创建一个Polyline对象,而不是现在创建的QGraphicsPathItem对象:
QGraphicsPathItem* new_item = new Polyline(pPath);请记住修改Polyline构造函数以选择路径,并将其转发给基类QGraphicsPathItem类。
另一个改进是认识到drawPolyline根本不需要成为成员函数。而且它的名字相当糟糕。我建议您将其定义为源文件本地函数,改为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();
}https://stackoverflow.com/questions/71071298
复制相似问题