簡體   English   中英

當 QFileDialog::getExistingDirectory 處於活動狀態時 QSerialPort 停止響應

[英]QSerialPort stops responding while QFileDialog::getExistingDirectory is active

我的應用程序在使用QFileDialog::getExistingDirectory時停止使用 QSerialPort 接收數據。 它在對話框關閉后恢復接收數據。 有沒有辦法防止這種情況?

您正在調用阻塞方法。 當該方法執行時,事件循環無法運行,因為它位於調用堆棧底部的某個位置,等待您的插槽返回到它。 這是同步編碼方式,並不能反映實際發生的情況,因為世界是異步的。 所以不要這樣編碼。

相反,您應該在文件對話框不可見時設置它,然后show()它,並在連接到QDialog::accepted()信號的插槽中執行所需的代碼。

您可以考慮設置並擁有一個不錯的異步助手,類似於getExistingDirectory

template <typename F> void withExistingDirectoryDo(F && fun, QObject * context = 0,
  QWidget * parent = 0, const QString & caption = QString(),
  const QString & dir = QString(), Options options = QFileDialog::ShowDirsOnly) {
  auto * dialog = new QFileDialog(parent);
  auto helper = [fun, dialog]{ fun(dialog->directory()); };
  if (context)
    connect(dialog, &QDialog::accepted, context, helper);
  else
    connect(dialog, &QDialog::accepted, helper);
  dialog->setAttribute(Qt::WA_DeleteOnClose);
  dialog->setOptions(options);
  dialog->setFileMode(QFileDialog::Directory);
  dialog->show();
}

下面是代碼轉換:

void before() {
  foo();
  auto dir = QFileDialog::getExistingDirectory(); // bad synchronous code
  bar(dir);
}

void after() {
  foo();
  withExistingDirectoryDo([this](const QDir & dir) {
    bar(dir);
  }, this);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM