【问题标题】:Qt - children set font breaks positioningQt - 儿童设置字体中断定位
【发布时间】:2016-10-19 20:52:54
【问题描述】:

好的,所以我开始使用 Qt 制作游戏,这样我就可以同时学习 Qt 和 C++ :D 但是,我现在遇到了一个问题。

我正在尝试使用QGraphicsRectItem 作为容器(父级)和QGraphicsTextItem 作为文本本身(子级)来创建一个文本框。我面临的问题是孩子与父母的相对位置。如果我在QGraphicsTextItem 上设置字体,则定位将完全错误,并且会流到容器之外。

文本框.h:

#ifndef TEXTBOX_H
#define TEXTBOX_H

#include <QGraphicsTextItem>
#include <QGraphicsRectItem>
#include <QTextCursor>
#include <QObject>

#include <qDebug>
class TextBox: public QObject, public QGraphicsRectItem {
    Q_OBJECT
public:
    TextBox(QString text, QGraphicsItem* parent=NULL);

    void mousePressEvent(QGraphicsSceneMouseEvent *event);

    QString getText();

    QGraphicsTextItem* playerText;
};

#endif // TEXTBOX_H

文本框.cpp

#include "TextBox.h"

TextBox::TextBox(QString text, QGraphicsItem* parent): QGraphicsRectItem(parent) {
// Draw the textbox
    setRect(0,0,400,100);
    QBrush brush;
    brush.setStyle(Qt::SolidPattern);
    brush.setColor(QColor(157, 116, 86, 255));
    setBrush(brush);

// Draw the text
    playerText = new QGraphicsTextItem(text, this);
    int xPos = rect().width() / 2 - playerText->boundingRect().width() / 2;
    int yPos = rect().height() / 2 - playerText->boundingRect().height() / 2;
    playerText->setPos(xPos,yPos);
}

void TextBox::mousePressEvent(QGraphicsSceneMouseEvent *event) {
    this->playerText->setTextInteractionFlags(Qt::TextEditorInteraction);
}

Game.cpp(用于创建对象等的代码所在的位置 - 仅包括相关部分):

// Create the playername textbox
    for(int i = 0; i < players; i++) {
        TextBox* textBox = new TextBox("Player 1");
        textBox->playerText->setFont(QFont("Times", 20));
        textBox->playerText->setFlags(QGraphicsItem::ItemIgnoresTransformations);
        scene->addItem(textBox);
    }

使用QGraphicsTextItem的默认字体和大小:

QGraphicsTextItem设置字体和大小:


如您所见,问题是当我设置字体和大小时,文本不再位于父元素的中心。 (请不要因为糟糕的代码而责备我,我对 Qt 和 C++ 都很陌生,我这样做只是为了学习)。

【问题讨论】:

  • 从风格的角度来看,除非你需要它们,否则不要从 QObject 继承或添加 Q_OBJECT 宏。它们增加了不必要的开销。
  • RobbieE,该类稍后可能需要一个信号/插槽,所以我决定添加它,以免忘记它。如果不使用,我将删除 QObject :P

标签: c++ qt qgraphicsitem qgraphicstextitem


【解决方案1】:

您在构造函数中调用boundingRect() 方法,因此在字体设置为其最终值之前设置了位置。如果您创建一个方法来设置位置并在设置字体之后调用它,或者在构造函数中设置位置之前设置字体,它应该可以工作。

【讨论】:

  • 哦,哇。那是我犯的一个愚蠢的错误。太感谢了。我将 setFont() 移到构造函数中,在 boundingRect() 之前,这解决了问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
相关资源
最近更新 更多