gpt4 book ai didi

c++ - 自定义 QGraphicsItem 和重绘问题

转载 作者:太空宇宙 更新时间:2023-11-04 14:13:00 48 4
gpt4 key购买 nike

全部,我实现了一个 QGraphicsItem,它是一个多边形。我通过使用 QGraphicsEllipseItem 作为点(用于拖动功能)加快了开发速度。但是,我现在在 update() 功能方面遇到了困难。我的代码贴在最后,我的问题是:

  1. 我在这里采取的方法是否正确?我开始怀疑自己
  2. 我应该在我的实现中调用 QGraphicsItem::update() 吗?我经常调用它

一些其他信息:

  • 我做了一个肮脏的小黑客。在我的实际代码中,我还继承自 QObject。这允许我在 scene() 上安装一个 eventFilter(我知道它是使用 itemChange 设置的)。从场景中,我在鼠标移动期间过滤 QGraphicsSceneMouseEvent 并调用 QGraphicsItem::update() 否则我的线条不会被重绘。
  • 当我现在从场景中移除 InteractivePolygon 时,我的线条并没有被移除!我必须调用 scene()->update。我觉得有些不对劲。

声明:

class InteractivePolygon : public QGraphicsItem
{

public:
//Only important methods
QRectF boundingRect() const;
void paint(bla bla bla);
bool eventFilter(QObject *, QEvent *);

private:
QList<QGraphicsEllipseItem *> m_points;

void AddPolygonPoint(QPointF);
QGraphicsEllipseItem * MakeNewPoint(QPointF);
}

实现:

QRectF InteractivePolygon::boundingRect() const
{
return childrenBoundingRect();
}

void InteractivePolygon::paint(QPainter painter.. otherstuf)
{
QPen line_pen(QColor(255,0,0));
painter->setPen(line_pen);

if(m_points.count() > 1)
{
for(int i = 1; i < m_points.count(); ++i)
painter->drawLine(m_points[i-1]->pos(), m_points[i]->pos());
}
}

void AddPolygonPoint(QRectF point)
{
QGraphicsEllipseItem * new_item = MakeNewPoint(point);
new_item->setParent(this);

m_points->push_front(new_item);

update();
}

QGraphicsEllipseItem * InteractivePolygon::MakeNewPoint(QPointF & new_point)
{
QGraphicsEllipseItem * result = 0;
result = new QGraphicsEllipseItem();
result->setPos(new_point);
result->setRect(-4, -4, 8, 8);
result->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable)

return result;
}

//Lets pretend this method is correctly setup/exists
bool InteractivePolygon::eventFilter(QObject *object, QEvent *event)
{
if(event->type() == QEvent::QEvent::GraphicsSceneMouseMove)
{
QGraphicsSceneMouseEvent * mouse_move = (QGraphicsSceneMouseEvent *)event;
//Selected index is set else, let's assume it works
if(selected_index)
{
update(); //If I don't do this, my lines in my paint() are not redrawn.
}
}
}

最佳答案

解决方案是 prepareGeometryChange() 每次我更改项目中的任何内容都会更改其边界框。一切都正确重绘并根据需要更新。

这允许我删除所有 update() 调用。

关于c++ - 自定义 QGraphicsItem 和重绘问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13278281/

48 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com