Handling gui with different threads

2019-08-20 10:01发布

I'm new in qt and c++, and I have a problem with threads.

For example, if I have a gui with two QPushButton and one QTextEdit, is it possible to set values to the QTextEdit from a thread (different from the gui main thread) without freezing the gui?

// These are the values that I want to set from the thread  
for(i=0;i<100;i++){  
     qtextedit.setText(i);  
}

2条回答
啃猪蹄的小仙女
2楼-- · 2019-08-20 10:20

You shouldn't use your example directly in another thread. However, it isn't too difficult to work things into a good form using signals and slots.

class UpThread : public QThread
{
    Q_OBJECT
    ...
public slots:
    void countUp() 
    {
        for ( int i = 0; i < 100; ++i )
        {
             emit  ( newText( QString::number( i ) ) );
             sleep( 1 );
        }
    }

signals:
    void newText( QString text );
}

class DownThread : public QThread
{
    Q_OBJECT
    ...
public slots:
    void countDown() 
    {
        for ( int i = 100; i > 0; --i )
        {
             emit  ( newText( QString::number( i ) ) );
             sleep( 1 );
        }
    }

signals:
    void newText( QString text );
}

int main( int argc, char **argv )
{
    QApplication app( argc, argv );
    MainWindow window;
    UpThread up;
    DownThread down;
    QObject::connect( window.buttonUp, SIGNAL( clicked() ), &up, SLOT( countUp() ) );
    QObject::connect( &up, SIGNAL( newText( QString ) ), &window.textEntry, SLOT( setText( QString ) ) );
    QObject::connect( window.buttonDown, SIGNAL( clicked() ), &down, SLOT( countDown() ) );
    QObject::connect( &down, SIGNAL( newText( QString ) ), &window.textEntry, SLOT( setText( QString ) ) );

    window.show();
    up.run();
    down.run();

    return ( app.exec() );
}

Note: I haven't compiled or tested this. Up and down don't care if the other is running, so if you click both buttons, your text entry may jump all over the place. I obviously left out a lot of stuff. I also added a sleep( 1 ) to each loop to show that they shouldn't block the main UI.

查看更多
SAY GOODBYE
3楼-- · 2019-08-20 10:21

It is possible: either use a signal/slot with a queued connection, or post events to the GUI thread.

Your example is fast enough to not block the GUI though.

查看更多
登录 后发表回答