3

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 ?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.