QGraphicsView Scale & QGraphicsRectItem 绘画未能调用
Posted
技术标签:
【中文标题】QGraphicsView Scale & QGraphicsRectItem 绘画未能调用【英文标题】:QGraphicsView Scale & QGraphicsRectItem paint failed to called 【发布时间】:2017-06-20 10:07:55 【问题描述】:我的工作环境:Qt 5.8 MSVC2015 64bit, QT GraphicsView, QGraphicsRectItem, Windows 7 64 bit。
问题: 当我放大和缩小 GraphicsView 时,我调用 GraphicsView 缩放方法。但是当我将 QGraphicsRectItem 添加到场景时,它无法调用它的绘制方法。
我的班级层次结构:
class GraphicsView : public QGraphicsView
class mySquare : public QObject, public QGraphicsRectItem
class Scene : public QGraphicsScene
代码:
//////*****在QGraphicsRectItem中绘制矩形*****///////////
void mySquare::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
QRectF rect(0,0,_width,_height);
painter->drawRect(rect);
void GraphicsView::wheelEvent(QWheelEvent * event)
int angle = event->angleDelta().y(); // angle will tell you zoom in or out.
double scaleFactor = 1.15; //How fast we zoom
setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
if (angle > 0)
qDebug()<<"Zoom in";
scale(scaleFactor, scaleFactor);
else
qDebug()<<"Zoom out";
scale(1.0 / scaleFactor, 1.0 / scaleFactor);
mySquare _square = new mySquare(0,blankImage);
_square->setPos(QPointF(0, 0));
//add square to scene.
//Bug!!! Why after scale function call, _square failed to draw rect in paint method.
_scene->addItem(_square);
_square->update();
这里是 git code
我花了几天和几个小时,但仍然无法找出为什么 QGraphicsRectItem 在调用 scale 方法时无法打印。任何建议都受到高度赞赏?
【问题讨论】:
行“mySquare _square = new mySquare(0,blankImage);”不会编译。请编辑您的问题以显示真实代码。 更新了 git 代码 url:github.com/SandyWare/ImageRender 注意扩展自QObject
和QGraphicsRectItem
有一个专门用于此目的的类QGraphicsObject
@Elia:谢谢,我已经更改了 mySquare 类:public QGraphicsObject
【参考方案1】:
感谢所有帮助。我通过覆盖 QGraphicsView scale 方法找到了解决方案。 变化 : 类 mySquare : 公共 QGraphicsObject
void GraphicsView::scale(qreal scaleFactor)
QRectF r(0, 0, 1, 1); // A reference
qreal factor = transform().scale(scaleFactor, scaleFactor).mapRect(r).width(); // absolute zoom factor
( (rFactor > 0 )
qDebug()<<"Zoom in";
else
qDebug()<<"Zoom out";
mySquare _square = new mySquare(0,blankImage);
_square->setPos(QPointF(0, 0));
_scene->addItem(_square);
_square->update();
QGraphicsView::scale(scaleFactor, scaleFactor);
【讨论】:
以上是关于QGraphicsView Scale & QGraphicsRectItem 绘画未能调用的主要内容,如果未能解决你的问题,请参考以下文章
如何去除QGraphicsView&Scene上添加的QPushButton的边界线
从 QGraphicsScene/QgraphicsItemGroup/QGraphicsView 中正确删除项目