简体   繁体   English

如何在新线程中创建QInputDialog?

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

Basically I'm calling a function from another thread using QtConcurrent . 基本上,我是使用QtConcurrent从另一个线程调用函数的。

Working as expected but once I create a QInputDialog within the called function, I'm getting an assertion exception telling me that I have to create the Dialog in the Main GUI Thread. 可以正常工作,但是一旦在被调用函数中创建了QInputDialog ,就会收到一个断言异常,告诉我必须在主GUI线程中创建Dialog。

To be more specific this line: 更具体地说,此行:

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

Now the question would be how can I call the Dialog from a new thread without too much extra work. 现在的问题是,如何在没有太多额外工作的情况下从新线程调用对话框。

You can't create widgets outside from main thread. 您不能在主线程之外创建小部件。 You can emit signal from network thread and create dialog in main thread. 您可以从网络线程发出信号,并在主线程中创建对话框。

Or do something like this (pseudo-code): 或执行以下操作(伪代码):

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