繁体   English   中英

如何在新线程中创建QInputDialog?

[英]How to create a QInputDialog in a new thread?

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

可以正常工作,但是一旦在被调用函数中创建了QInputDialog ,就会收到一个断言异常,告诉我必须在主GUI线程中创建Dialog。

更具体地说,此行:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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