[英]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.