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) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); QGraphicsScene *scene = new QGraphicsScene(); scene->addText("Hi"); ui->graphicsView->setScene(scene); } MainWindow::~MainWindow() { 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; ui->graphicsView->setScene(foo.scene);
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.cppstd::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 ?
ThanksP.S.: Where shall I post newbie question ?
-
Hi and welcome to devnet,
@Sayanel said in Displaying a text in a QGraphicsScene:MyClass foo;
ui->graphicsView->setScene(foo.scene);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. -
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.
-
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 (https://doc.qt.io/qt-5/qtwidgets-graphicsview-chip-example.html) which I think does what I want (via its class 'View')