简体   繁体   English

用不同的线程处理GUI

[英]Handling gui with different threads

I'm new in qt and c++, and I have a problem with threads. 我是qt和c ++的新手,线程有问题。

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? 例如,如果我有一个带有两个QPushButton和一个QTextEdit的gui,是否可以在不冻结gui的情况下从一个线程(与gui主线程不同)为QTextEdit设置值?

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

It is possible: either use a signal/slot with a queued connection, or post events to the GUI thread. 可能的是:要么使用带有排队连接的信号/插槽,要么将事件发布到GUI线程。

Your example is fast enough to not block the GUI though. 您的示例足够快,不会阻塞GUI。

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. 我还向每个循环添加了一个sleep( 1 )以表明它们不应阻止主UI。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM