Show / hide QFrame ouside main thread



  • Hiho,
    I'm programming a game and want to display a menu if the player hits F1 and hide the menu again if Esc is hitten.
    The problem is that the game crashes as soon as I invoke menuFrame->show() or setShown(true).
    I think the reason is that I call the function in the game thread and not in the mainthread.
    Since I only have two choices:
    Call the function in the game mainloop if a variable gets true
    or
    from a slot bound on the F1 key

    I dont know how to show or hide this frame.

    In some Posts on various forums I read that I have to call postevent for manipulate widgets outside the main thread.
    The problem is that I don't know how to do that, and I didn't find any examples on showing / hiding widgets with postevent.

    Can somebody point me to the right direction or maybe provide a little code snippet so that I know how to use postevent for showing / hiding a widget?

    Thanks in advence and have a nice day
    Ritschratsch


  • Moderators

    [quote author="ritschratsch" date="1369244967"]I think the reason is that I call the function in the game thread and not in the mainthread.[/quote]That's correct.

    [quote]In some Posts on various forums I read that I have to call postevent for manipulate widgets outside the main thread.[/quote]postEvent() is a bit lower-level -- I find "signal/slot connections":http://qt-project.org/doc/qt-5.0/qtcore/signalsandslots.html easier to use. You can emit a signal when a key is pressed, and connect it to the show()/hide() slots.

    In your other thread, create signals called "f1Pressed" and "escPressed", and then emit them when the keys are pressed:
    @
    // Replace "menuFrame->show();" with:
    emit f1Pressed();

    // Replace "menuFrame->hide();" with:
    emit escPressed();
    @

    In the place where menuFrame is created, connect the key-pressed signals to your QFrame's slots:
    @
    QObject::connect(objectInOtherThread, SIGNAL(f1Pressed()), menuFrame, SLOT(show()));
    QObject::connect(objectInOtherThread, SIGNAL(escPressed()), menuFrame, SLOT(hide()));
    @



  • Thank you jksh, it works fine now :)


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.