A error when I use QTab setcurrentIndex()



  • The code is like
    @ui->connectTab->setCurrentIndex(4);@

    The Qt creator returns an error after running this sentence.
    The error message:
    @<unknown>: Fatal IO error 11 (Resource temporarily unavailable) on X server :0.0.
    Debugging has finished@

    My program is a like a front UI and a backstage server-client. I guess the reason is because that setCurrentIndex is called in a children thread( I used fork to create a client which keeps listening incoming socket message). How can I make children thread to operate the UI created in the main thread?

    I checked the ui' s values in the parent and children thread, they are the same.

    Many thanks



  • Try to use queued signals/slots. For this, you can either use

    @QMetaObject::invokeMethod(tabWidget, "setCurrentIndex", Qt::QueuedConnection, Q_ARG(int, index))@

    or connect some signal to setCurrentIndex(index) slot of QTabWidget, with Qt::QueuedConnection connection type, and emit this signal from your child thread:

    @QObject::connect( objectFromChildThread, SIGNAL(someSignal(int)), tabWidget, SLOT(setCurrentIndex(int)), Qt::QueuedConnection );@

    Here is an example:

    @class MyThread : public QThread
    {
    Q_OBJECT

    public:
    void run()
    {
    QTime time;
    time.start();

        while ( true ) {
            if ( time.elapsed() > 300 ) {
                // Use this
                QMetaObject::invokeMethod( tabWidget, "setCurrentIndex", 
                    Qt::QueuedConnection, Q_ARG(int, rand()%2) );
                // Or this
                //emit setCurrentIndex( rand() % 2 );
                time.start();
            }
        }
    }
    
    QTabWidget* tabWidget;
    

    signals:
    void setCurrentIndex( int );
    };

    int main( int argc, char** argv )
    {
    QApplication app( argc, argv );

    QTabWidget* tabs = new QTabWidget();
    tabs->addTab( new QWidget(), "tab1" );
    tabs->addTab( new QWidget(), "tab2" );
    tabs->show();
    
    MyThread* thread = new MyThread();
    thread->tabWidget = tabs;
    QObject::connect( thread, SIGNAL(setCurrentIndex(int)),
        tabs, SLOT(setCurrentIndex(int)), Qt::QueuedConnection );
    
    thread->start();
    
    return app.exec();
    

    }@

    In both cases, setCurrentIndex() slot is pushed into the application queue and invoked later from the main thread. If you want your child thread to wait until the slot return, use Qt::BlockingQueuedConnection.

    Sorry for my english =)



  • Thanks a lot. I tried the second one, it perfectly works.

    Cheers


Log in to reply
 

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