我是 Qt 的新手,想撰寫代碼來更改 Qt 的默認選擇行為。所以我試圖覆寫虛擬繪畫方法。但是paint方法沒有被呼叫。
在下面的代碼中,只需列印折線,paint() 會嘗試更改其選擇行為。
折線.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();
};
折線.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;
}
主檔案
#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();
}
我哪里錯了?
uj5u.com熱心網友回復:
問題是您沒有創建任何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://www.uj5u.com/shujuku/429976.html
標籤:C qt qt5 qgraphicsview qgraphics场景
上一篇:QDialog::move()不考慮具有多個螢屏的Ubuntu上的任務欄
下一篇:改進變數呼叫
