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 :

    Here is set an ellipse item and I have the function to set the position in the scene

    Here I set a scene in a rect
    Is a Qwidget element
    I can show the objects like this:

    scene=new QGraphicsScene(this);
    object1=new object();
    //that works well


    Here I have an infinite loop to receive packets:
    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



    Scene *scene=new Scene(this);

    int main(int argc, char *argv[])
    QApplication a(argc, argv);
    MainWindow w;
    Thread t;
    //start the trhead

    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 works

    I'll appreciate any help.

  • Lifetime Qt Champion

    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.

  • Lifetime Qt Champion

    In that case start by reading the Signals & Slots chapter in Qt's documentation.

    And the QThread documentation.

Log in to reply