PDA

View Full Version : Problem with QGraphicsTextItem



johnkrusty
20th October 2012, 10:11
I have a class


class Letter : public QGraphicsTextItem
{
public:
Letter();
~Letter();
void setText(const QString &text);
QString getText();
protected:
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
QRectF boundingRect() const;
QPainterPath shape() const;

private:
QString myText;
QTextOption myTextOption;
};



Letter::Letter()
{
myTextOption.setAlignment(Qt::AlignCenter);
myTextOption.setWrapMode(QTextOption::WrapAtWordBo undaryOrAnywhere);
}

Letter::~Letter() {

}

QRectF Letter::boundingRect() const {
return QRectF(0,0,145,145);
}

QPainterPath Letter::shape() const {
QPainterPath path;
path.addRect(boundingRect());
return path;
}

void Letter::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
painter->fillRect(boundingRect(),Qt::red);
painter->setPen(Qt::white);
painter->setFont(QFont("Open Sans", 60));
painter->drawText(boundingRect(),myText,myTextOption);
QGraphicsTextItem::paint(painter,option,widget);
}

void Letter::setText(const QString &text) {
myText = text;
this->update();
}

QString Letter::getText() {
return myText;
}

I add letters to QGraphicsScene


class GameField : public QGraphicsScene
{
public:
GameField();
};

GameField::GameField()
{
this->setBackgroundBrush(QBrush(QColor(230,230,230),Qt:: SolidPattern));
for (int i = 10; i < 610; i += 150) {
for (int j = 10; j < 610; j += 150) {
Letter *letter = new Letter();
letter->setText(QString('A'+qrand()%26));
this->addItem(letter);
letter->setPos(i, j);
}
}
}

but when I try to click on any letter, my program crashes.

norobro
21st October 2012, 05:46
Why not use the QGraphicsTextItem getter/setter methods setPlainText() and toPlainText()?

Then in your painter do this:
void Letter::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
. . .
painter->drawText(boundingRect(),toPlainText(),myTextOption );
//QGraphicsTextItem::paint(painter,option,widget);
}

johnkrusty
21st October 2012, 10:09
Thank you for your response, it solved my problem with a crash. But now I have 2 letters inside the rectangle: first in the center (with QTextOption and Qpen white), second black (standard).

norobro
21st October 2012, 15:55
Removing the call to the parent class paint function (QGraphicsTextItem::paint()) should get rid of the black letter(s).


void Letter::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
painter->fillRect(boundingRect(),Qt::red);
painter->setPen(Qt::white);
painter->setFont(QFont("Open Sans", 60));
painter->drawText(boundingRect(),toPlainText(),myTextOption );
}

johnkrusty
21st October 2012, 20:29
Thanks, it's working perfectly now.