简体   繁体   中英

How to create a QInputDialog in a new thread?

Basically I'm calling a function from another thread using 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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