简体   繁体   中英

Qt how to implement a process loop?

I'm beggining with Qt and I'm currently adapting a command-line program to use it with a GUI.

I'm building my GUI like this :

int main(int argc, char *argv[])    
{    
    QApplication a(argc, argv);    
    MainWindow w;    
    w.show();    
    return a.exec();    
}    

I want to process some events permanently. In command line, I used a while loop, it work perfectly. Using Qt, I don't know how I can process these events properly. So I tried to use a std::thread, but my Qt app crashes when I try to modify the GUI from the thread. Same problem using QThread. I don't need threading, so it would be great if I can just put my code in the Qt's main thread.

Anyone can help me please ?

You could use a QTimer connected to a slot in your MainWindow class to run a function periodically like this :

MainWindow::MainWindow()
{
    myTimer = new QTimer();
    myTimer->setSingleShot(false);
    myTimer->start(intervalInMilliseconds);
    connect(myTimer, &QTimer::timeout, this, &MainWindow::handleMyEvents);
}

void MainWindow::handleMyEvents()
{
    // Your code here
}

You could also use threads, but note that you must not call any GUI code from any thread that isn't the QApplication thread, this is probably why your attempt crashed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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