I have a QT-project (using C++) where instances of a certain user-defined QGraphicsItem called Person move around the scene. Sometimes those Persons interact so that some of them change color.
Now I want to put a text field in the window and display counts of how many I have of each color. But since the change occurs within the call to the Person::advance-method I want to create a text field that can be updated from within these.
I could easily display some text by adding the following code to my main.cpp:
QGraphicsSimpleTextItem *text1 = new QGraphicsSimpleTextItem;
text1->setPos(-200, -150);
text1->setText("This is an arbitrary English sentence");
scene.addItem(text1);
but I do not know how to access and alter the text of this variable text1 from within the advance-method of the Persons in my scene. What is a good strategy for this?
Should I create a global variable keeping track of the count, and if I do, how can I then update the text field? Or should the text not even be on my
QGraphicsScene, but rather be defined in some other more appropriate place where it is callable from everywhere in the program? Is there a generic way of doing this?
You could subclass
QGraphicsObjectinstead ofQGraphicsItem, that would allow you to use signals from within the Person class. Then just emit a signal to a slot that counts the items and changes the text of text1.What I would do is move your graphics view to a new
QWidgettype class (likeQMainWindow). This is to make it easier to handle signals and slots, and it will also allow you to use member variables. It will also be cleaner than doing everything inmain.cpp.You could have your
text1variable as a member variable of thisMainWindowclass. This would make accessing it easy.Your slot in the
MainWindowclass could look something like this:You can improve the logic, but this is just a basic example.