如何在新线程中创建 QInputDialog?

How to create a QInputDialog in a new thread?

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

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

更具体地说,这一行:

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

现在的问题是如何在不做太多额外工作的情况下从新线程调用对话框。

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

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

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;
}