jeudi 16 juillet 2020

How to properly position a QGraphicsTextItem on a QGraphicsScene

The probelm I have is that I am trying to position a QGraphicsTextItem on a specific location of my QGraphicsScene , to be precise in the center of the speedometer below. But nothing I tried seems to work properly. Despite I clearly provided the coordinates I want the QGraphicsTextItem, it still anchored on top-left as shown below: Below the snippet of code:

speedwidget.cpp

SpeedWidget::SpeedWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::SpeedWidget)
{
    ui->setupUi(this);
    mScene = new Scene(this);
    ui->graphicsView->setScene(mScene);

    io = new QGraphicsTextItem;
    io->setPos(210,240);
    QFont *f = new QFont;
    f->setPointSize(18);
    io->setFont(*f);
    mScene->addText("Odometer :")->setDefaultTextColor(Qt::red);
    mScene->addItem(io);
}

speedwidget.h

class SpeedWidget : public QWidget
{
    Q_OBJECT
public:
    SpeedWidget(QWidget *parent = nullptr);
    ~SpeedWidget();

private:
    Ui::SpeedWidget *ui;
    Scene *mScene;
    QGraphicsTextItem *io;

};
#endif // SPEEDWIDGET_H

item

What I tried so far to solve the problem was:

  1. I consulted this post which explained the idea but I don't need to change the background color in this example.

  2. This one had a good snippet, but I am not trying to highlight the color. I am only trying to position the text on a specific location.

  3. If I change io->setPos(210,240); and give different numbers, I still see it anchored on top-left.

Thanks for pointing to the right direction for solving this issue.

Aucun commentaire:

Enregistrer un commentaire