Important: Please read the Qt Code of Conduct -

Qt thread connect to qml

  • I have a main program that create a QDeclarativeView for qml file, and also create a thread.
    i want that the qml file will send signal to start the thread running. this is what i do:

    this is working, but this thread need to change a context property in the view when he is running.
    when I do this the program end with memory error.

    void MyThread::run()
    m_view->rootContext()->setContextProperty("newProperty", "blabla");

    I init the m_viewto be pointer to the view in the thread constructor, and I don't know why this failed.

    any idea??

  • It is not allowed to access UI things inside a thread. Your thread must emit a signal which is handled in the main thread then.

  • But when i wait for a while before the initialization in the thread it works...

    @void MyThread::run()
    int i=0;
    m_view->rootContext()->setContextProperty("newProperty", "blabla");


  • Moderators

    If it works, it's just by pure luck and happenstance. As Gerolf said, you can't access UI things inside of a thread.

    By when they say you can't, it means that while there is nothing that keeps you from trying to access things from your thread, the underlying system is not designed to handle those accesses properly and the results are undefined. That means that in certain situations things could appear to work, but it's not expected, proper, or guaranteed to be repeatable.

  • Is this valid also when the property i initialize in the qml from the thread,
    (m_view->rootContext()->setContextProperty("newProperty", "blabla");
    ) is used in other qml file , and not from the current qml file that running?

  • Moderators

    If you're directly accessing m_view from anywhere other than the main thread, it's incorrect and invalid.

Log in to reply