Important: Please read the Qt Code of Conduct -

Displaying a text in a QGraphicsScene

  • This is a newbie I am trying to create a scene with Qt to display what I want (lets say for now just a text), but with the code describing the content being in another class.

    I have a mainwindows, created with QtCreator gui, which contains the widget "graphicView"
    In my mainwindows.cpp, I can do :

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    #include <QtWidgets>
    #include <QGraphicsScene>
    MainWindow::MainWindow(QWidget *parent) :
        ui(new Ui::MainWindow)
        QGraphicsScene *scene = new QGraphicsScene();
        delete ui;

    And it will display the text ('Hi!'). Now what I want to have is a class MyClass in charge of what is inside the widget graphicsView, and do in mainwindows.cpp:

    MyClass foo;

    with MyClass.h having

    QGraphicsScene *scene;

    and MyClass.cpp, in the constructor of the class :

    scene = new QGraphicsScene(this);
    scene->addtext("Hi again!");

    But when running it it doesn't work, it doesn't display anything.
    If I add this at the end of the mainwindows.cpp

    std::cout << foo.scene->items().size() << std::endl;

    I can see that my scene do contains one element, but for some reason it isn't displayed. Any hint why ?

    P.S.: Where shall I post newbie question ?

  • Lifetime Qt Champion

    Hi and welcome to devnet,
    @Sayanel said in Displaying a text in a QGraphicsScene:

    MyClass foo;

    What it is the lifetime of foo ?

    If it's declared in the same method where you make the ui call, then it will be destroyed before anything else happens.

  • If think that is is, foo is deleted at the end of the mainwindow constructor. Thank you sir ! I just have to do in the mainwindow.cpp:

        MyClass *foo = new MyClass;

  • Lifetime Qt Champion

    Except that now you are leaking memory as this object pointer gets lost.

    You should make it a member of your MainWindow class and handle it's destruction properly. Or use e.g QScopedPointer to store it.

  • What if I just declare foo as a child of mainwindow

    MyClass *foo = new MyClass(this);

    it will be destructed when I close my mainwindow ?

  • Lifetime Qt Champion

    If MyClass is a QObject based class. But if you need that kind of stuff for a pretty simple task the way you want to do it. you might want to reconsider its design.

  • Well MyClass inherits from QWidget
    The idea I had was to have MyClass handle everything inside my 'graphicsView' -in order to not have it pollute the main windows-. This way I can interact with the scene using MyClass method and I can have it have slots.
    The idea is to crate a zone (foo.scene, displayed on the widget graphicsView) where I will be able to put all the object I want at the position I want.

    I found this example ( which I think does what I want (via its class 'View')

Log in to reply