Update scene with a thread
-
Hi ,
I'm doing a program that recieves packets of information that contains the position of an object,
I can read this packets but I don't know how to update the scene where I show the objects.
I have the next files :Object.cpp
Here is set an ellipse item and I have the function to set the position in the scenescene.cpp:
Here I set a scene in a rect
Is a Qwidget element
I can show the objects like this:[code]
ui->setupUi(this);
scene=new QGraphicsScene(this);
ui->graphicsView->setScene(scene);
scene->setSceneRect(....)
object1=new object();
object1->setCord(...,...)
scene->addItem(object1);
//that works wellthread.cpp
Here I have an infinite loop to receive packets:
[code]
while(true)
{
if(recieve packet){
//read the packet
// print(packet posx and posy)
//I can see the info in the console
//here I tried to call the scene like(not exactly):
object1->setCoord(packet posx, packet posy);
//Qt doesn't show any problems here but the ui doesn't update the scene}
}
Mainwindow.cpp
[code]
ui->setupUi(this);
Scene *scene=new Scene(this);
setCentralWidget(scene);Main.cpp
[code]
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
Thread t;
//start the trhead
t.start();return a.exec();
}
I have more file in the program and their headers but here you can see the most important part of it.
I think that the function connect() can help but I don't how it worksI'll appreciate any help.
-
Hi and welcome to devnet,
First thing: don't modify GUI elements directly from a thread. This should be done in the GUI thread.
Second: based on your code, there's no link between your thread the your MainWindow so you are not modifying the object you think you are modifying.What you should do is emit the new position from your Thread object and connect that to a slot that will update you object instance.
On a side note, please use meaningful names for your classes and variables. It will make thing easier to understand and talk about.
-
Hi,
Thanks for your answer , when you say this "you should do is emit the new position from your Thread object and connect that to a slot that will update you object instance."
How do I do that? Can you give an example for this? I'm new in Qt and I really appreciete your help.
Thanks! -
In that case start by reading the Signals & Slots chapter in Qt's documentation.
And the QThread documentation.