我找不到我做错了的地方。我想在发生特定事件时更改项目(QGraphicsRectItem)的颜色。事实是,似乎一旦调用了覆盖绘画方法,无论如何颜色都不会改变。这是我所做的简单代码:
item.h
class Item : public QGraphicsRectItem
{
public:
Item(QGraphicsView *graphView);
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *) override;
private:
QPointF newPos;
QGraphicsView *graph;
};
item.cpp
Item::Item(QGraphicsView *graphWidget) : graph(graphWidget) { }
void Item::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *)
{
painter->setPen(Qt::NoPen);
painter->setBrush(Qt::black);
painter->drawEllipse(-7, -7, 20, 20);
}
main.cpp
int main(int argc, char *argv[])
{
srand(QDateTime::currentDateTime().toMSecsSinceEpoch());
QApplication a(argc, argv);
QGraphicsScene scene;
QGraphicsView view(&scene);
Item *item = new Item(&view);
scene.addItem(item);
item->setPos(0, 0);
item->setBrush(Qt::red);
item->update();
view.show();
return a.exec();
}
最佳答案
如果我正确理解您的问题,那么问题是在item->setBrush(Qt::red)
之后,您的圈子没有被涂成红色。如果是这种情况,则问题是您在Qt::NoPen
函数中强行使用了特定的笔(Qt::red
)和画笔(paint
),而没有使用Item::pen()
和Item::brush()
来检索信息。相反,您可以执行以下操作:
Item::Item(QGraphicsView *graphWidget) : graph(graphWidget)
{
setPen(Qt::NoPen);
setBrush(Qt::black);
}
void Item::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *)
{
Q_UNUSED(option);
painter->setPen(pen());
painter->setBrush(brush());
painter->drawEllipse(-7, -7, 20, 20);
}
这样,您可以在构造函数中定义默认的画笔,但是仍然可以使用
Item::setPen
和Item::setBrush
对其进行更改。此外,对于此示例,您最好继承 QAbstractGraphicsShapeItem
,但随后必须实现Item::boundingRect
函数。下面的示例输出一个红色圆圈(这是我怀疑您要执行的操作),并且还用黑色绘制轮廓(尽管这不是您想要的,但是为了显示笔也会改变):#include <QApplication>
#include <QDateTime>
#include <QGraphicsRectItem>
#include <QGraphicsScene>
#include <QGraphicsView>
class Item : public QAbstractGraphicsShapeItem
{
public:
Item(QGraphicsView *graphView);
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *) override;
virtual QRectF boundingRect() const override;
private:
QPointF newPos;
QGraphicsView *graph;
};
Item::Item(QGraphicsView *graphWidget) : graph(graphWidget)
{
setPen(Qt::NoPen);
setBrush(Qt::black);
}
void Item::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *)
{
Q_UNUSED(option);
painter->setPen(pen());
painter->setBrush(brush());
painter->drawEllipse(-7, -7, 20, 20);
}
QRectF Item::boundingRect() const
{
double pw = pen().widthF() / 2;
return QRectF(QPointF(-7 - pw, -7 - pw), QSizeF(20 + 2 * pw, 20 + 2 * pw));
}
int main(int argc, char *argv[])
{
srand(QDateTime::currentDateTime().toMSecsSinceEpoch());
QApplication a(argc, argv);
QGraphicsScene scene;
QGraphicsView view(&scene);
Item *item = new Item(&view);
scene.addItem(item);
item->setPos(0, 0);
item->setBrush(Qt::red);
item->setPen(QPen(Qt::black));
item->update();
view.show();
return a.exec();
}
关于c++ - 如何更改QGraphicsRectItem的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62081156/