如何在新线程中创建QInputDialog?

时间:2015-03-28 17:37:58

标签: c++ multithreading qt qt5.4

基本上我使用QtConcurrent从另一个线程调用函数。

按预期工作但是一旦我在被调用函数中创建QInputDialog,我就会收到一个断言异常,告诉我必须在主GUI线程中创建对话框。

更具体地说,这一行:

password = QInputDialog::getText( this , tr( "Password" ) , tr( "Enter Password:" ) , QLineEdit::Password , selectedPassword , &ok );

现在的问题是如何在没有太多额外工作的情况下从新线程调用Dialog。

1 个答案:

答案 0 :(得分:1)

您无法在主线程外创建小部件。您可以从网络线程发出信号并在主线程中创建对话框。

或者做这样的事情(伪代码):

class NotificationManager : public QObject
{
  Q_OBJECT
//...
public slots:
  void showMessage( const QString& text )
  {
    if ( QThread::currendThread() != this->thread() )
    {
      QMetaObject::invoke( this, "showMessage", Qt::QueuedConnection, Q_ARG( QString, text );
      // Or use Qt::BlockingQueuedConnection to freeze caller thread, until dialog will be closed
      return;
    }
    QMessageBox::information( nullptr, QString(), text );
  }
};

class ThreadedWorker : public QRunnable
{
  ThreadedWorker( NotificationManager *notifications )
    : _notifications( notifications )
  {}

  void run() override
  {
    // Do some work;
    notifications->showMessage( "Show this in GUI thread" );
  }

private:
  NotificationManager *_notifications;
}