我正在使用Qt的QGraphicsView
- 和QGraphicsItem
- 子类。
有没有办法在视图矩形改变时不缩放视图中项目的图形表示,例如,放大时。默认行为是我的项目相对于我的视图矩形缩放。
我想要显示2d点,这些点应该由一个薄矩形表示,当在视图中放大时,该矩形不应缩放。请参阅典型的三维建模软件以供参考,其中顶点始终以相同的大小显示。
谢谢!
答案 0 :(得分:10)
将QGraphicItem
的标志QGraphicsItem::ItemIgnoresTransformations
设置为true对您不起作用?
答案 1 :(得分:4)
我遇到了同样的问题,我花了一段时间才弄明白。这就是我解决它的方法。
扩展QGraphicsItem类,覆盖paint()。 在paint()内部,将变换的缩放系数重置为1(m11和m22),并在复位前保存m11(x缩放系数)和m22(y缩放系数)。 然后,像往常一样画画,但是将你的x乘以m11和y乘以m22。这样可以避免使用默认变换进行绘制,但会根据场景的变换显式计算位置。
void MyItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *item, QWidget *widget)
{
QTransform t = painter->transform();
qreal m11 = t.m11(), m22 = t.m22();
painter->save(); // save painter state
painter->setTransform(QTransform(m11, t.m12(), t.m13(),
t.m21(), 1, t.m23(), t.m31(),
t.m32(), t.m33()));
int x = 0, y = 0; // item's coordinates
painter->drawText(x*m11, y*m22, "Text"); // the text itself will not be scaled, but when the scene is transformed, this text will still anchor correctly
painter->restore(); // restore painter state
}
以下代码块使用默认转换
进行绘制void MyItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *item, QWidget *widget)
{
int x = 0, y = 0;
painter->drawText(x, y, "Text");
}
你可以尝试两者看看差异。希望这可以帮助。
答案 2 :(得分:2)
这个怎么样:
#include <QtGui/QApplication>
#include <QtGui/QGraphicsScene>
#include <QtGui/QGraphicsView>
#include <QtGui/QGraphicsRectItem>
int main(int argc, char* argv[]) {
QApplication app(argc, argv);
QGraphicsScene scene;
scene.addText("Hello, world!");
QRect rect(50, 50, 100, 100);
QGraphicsRectItem* recti = scene.addRect(rect);
QGraphicsView view(&scene);
// Set scale for the view
view.scale(10.0, 5.0);
// Set the inverse transformation for the item
recti->setTransform(view.transform().inverted());
view.show();
return app.exec();
}
正如您所看到的那样,文本按比例放大但矩形不是。请注意,这不仅会阻止矩形的缩放,还会阻止其他转换。
答案 3 :(得分:1)
我发现如果我派出一个新类并重新修改我可以做的绘画功能
void MyDerivedQGraphicsItem::paint(QPainter *painter,
const QStyleOptionGraphicsItem *option,
QWidget *widget)
{
double scaleValue = scale();
double scaleX = painter->transform().m11();
setScale(scaleValue / scaleX);
QGraphicsSvgItem::paint(painter,option,widget);
}
到目前为止,这是我发现的最佳方式,但我仍然在修补。
答案 4 :(得分:1)
以下解决方案对我来说非常有用:
void MyDerivedQGraphicsItem::paint(QPainter *painter, const StyleOptionGraphicsItem *option, QWidget *widget)
{
double scaleValue = scale()/painter->transform().m11();
painter->save();
painter->scale(scaleValue, scaleValue);
painter->drawText(...);
painter->restore();
...
}
我们还可以将scaleValue乘以我们希望在保存/恢复环境之外保持其大小不变的其他方法。
QPointF ref(500, 500);
QPointF vector = scaleValue * QPointF(100, 100);
painter->drawLine(ref+vector, ref-vector);