c++qtqgraphicsitemqgraphicstextitem

Qt - children set font breaks positioning


Okay, so I've started making a game using Qt so that I can learn both Qt and C++ at the same time :D However, I'm stuck with an issue at the moment.

I'm trying to make a textbox using a QGraphicsRectItem as a container (parent), and a QGraphicsTextItem as the text itself (child). The problem I'm facing is the child's relative position to the parent. If I set a font on the QGraphicsTextItem, the positioning will be completely wrong, and it will flow outside of the container for that matter.

TextBox.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

TextBox.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 (where the code for creating the object and such is located - only included the relevant part):

// 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);
    }

Using the default font & size for the QGraphicsTextItem:

Default font & size

Setting a font & size for the QGraphicsTextItem:

Setting a font & size

The problem, as you may see, is that when I set a font and a size, the text is no longer in the center of the parent element. (Please do not unleash hell on me for bad code, I'm very new to both Qt and C++, and I'm doing this for learning purposes only).


Solution

  • You are calling the boundingRect() method in the constructor, so the position is set before the font is set to it's final value. If you either make a method to set the position and call it after setting the font or set the font before setting the position in the constructor it should work.