缩放时保持QGraphicsSimpleTextItem居中

时间:2018-03-05 14:29:08

标签: c++ qt

我想创建一个QGraphicsRectItem并使用QGraphicsSimpleTextItem显示其名称。我希望文本的大小不受缩放的影响。我还希望文本的位置以QGraphicsRectItem为中心。

到目前为止,这是我的尝试:

#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QGraphicsRectItem>
#include <QPen>
#include <QWheelEvent>
#include <cmath>
#include <QDebug>

class MainView : public QGraphicsView {
public:
  MainView(QGraphicsScene *scene) : QGraphicsView(scene) {  setBackgroundBrush(QBrush(QColor(255, 255, 255)));}
protected:
  void wheelEvent(QWheelEvent *event) {
    double scaleFactor = pow(2.0, event->delta() / 240.0);
    scale(scaleFactor, scaleFactor);
  }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QGraphicsScene scene;
    scene.setSceneRect(0, 0, 800, 800);
    QGraphicsRectItem* rectItem = new QGraphicsRectItem(QRectF(0, 0, 400, 200));
    rectItem->setPos(200, 200);
    rectItem->setBrush(QColor(255, 0, 0));
    scene.addItem(rectItem);

    QGraphicsSimpleTextItem *nameItem = new QGraphicsSimpleTextItem("name", rectItem);
    QFont f = nameItem->font();
    f.setPointSize(12);
    nameItem->setFont(f);
    nameItem->setFlag(QGraphicsItem::ItemIgnoresTransformations);
    nameItem->setPos(rectItem->rect().center());

    MainView view(&scene);
    view.show();

    return a.exec();
}

不幸的是,您可以在捕获时看到enter image description here,当我取消缩放时(右侧),文本不会留在矩形内。

如何将文本保留在矩形内并居中? 谢谢。

1 个答案:

答案 0 :(得分:1)

  

我还希望文本的位置集中在QGraphicsRectItem

您所看到的内容是正确的,因为您正在缩放QGraphicsView的左上角,文字项目位于矩形的中心。

如果您缩放QGraphicsRectItem的中心,则会看到文本将保持其在矩形中心的位置。

另一种看待这种情况的方法是将文本放在矩形的左上角。您会注意到,在此处缩放时,文本将显示正确,直到它不再适合矩形。

enter image description here

继续缩放,您会看到文本的左上角仍然位于中心,但由于文本不遵循变换,因此将其推到外面

enter image description here

可能看起来文本的左上角位于矩形下方,但文本的边界矩形会考虑重音(例如è)。

因此,通过将文本放在rect的中心而不是左上角,文本在rect之外的位置会加剧。

到目前为止缩小后,矩形的变换处理点大小的一小部分,但非变换文本不受影响,因此像素的0.6和0.9之间的差异是无关紧要的并将位于同一像素。

你需要考虑你想要实现的目标。是否真的有必要缩放到这个范围,还是可以将其限制在某一点以外,你不会注意到这个问题?

相关问题