Results 1 to 12 of 12

Thread: Communication between QThread and Yes/No QMessageBox?

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Join Date
    Oct 2006
    Posts
    279
    Qt products
    Qt4
    Platforms
    MacOS X Unix/X11 Windows
    Thanks
    6
    Thanked 40 Times in 39 Posts

    Default Re: Communication between QThread and Yes/No QMessageBox?

    As long as the tQThread object was created in the Gui thread, you can set up a connection between a private signal and a private slot. For the synchronization you need a QWaitCondition and a QMutex.
    e.g.:
    Qt Code:
    1. class WorkingThread : public QThread
    2. {
    3. Q_OBJECT
    4. public:
    5. WorkingThread(QObject*parent=0);
    6. protected:
    7. virtual void run();
    8. signals:
    9. void askAQuestion( const QString& question, QMessageBox::StandardButton* answer);
    10. private slots:
    11. void questionAsked(const QString& question, QMessageBox::StandardButton* answer);
    12. private:
    13. QWaitCondition waitCondition;
    14. QMutex mutex;
    15. };
    16.  
    17. WorkingThread::WorkingThread(QObject*parent)
    18. : QThread(parent=0)
    19. {
    20. connect(this, SIGNAL(askAQuestion( const QString&, QMessageBox::StandardButton*)),
    21. this, SLOT(questionAsked( const QString&, QMessageBox::StandardButton*)));
    22. }
    23.  
    24. void WorkingThread::run()
    25. {
    26. QMessageBox::StandardButton answer = QMessageBox::Yes;
    27. do
    28. {
    29. QMutexLocker locker(&mutex);
    30. emit askAQuestion( "do you want to continue?", &answer);
    31. waitCondition.wait(&mutex);
    32. }
    33. while(answer == QMessageBox::Yes);
    34. }
    35.  
    36. void WorkingThread::questionAsked(const QString& question, QMessageBox::StandardButton* answer)
    37. {
    38. QMutexLocker locker(&mutex);
    39. *answer = QMessageBox::question(0, "Question:", question, QMessageBox::Yes|QMessageBox::No);
    40. waitCondition.wakeOne();
    41. }
    To copy to clipboard, switch view to plain text mode 

    The connection will automatically be queued since the run() function doesn't reside in the same thread as the QThread object, thus it's safe to use a messagebox.

    Good luck!
    Attached Files Attached Files

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Qt is a trademark of The Qt Company.