[英]Error when display an error message box. How can i display it?
我嘗試顯示一個錯誤消息框,但是發生了錯誤。 誰能幫忙檢查我的編碼?
void smtp_listener::pop3Stat(QString reply)
{
print_D(FUNC);
if(reply.contains("+OK"))
{
*t << "stat" <<"\r\n";
t->flush();
setState(POP3_Read);
}
else
{
print_E("ERROR :"+reply,FUNC,__LINE__);
QMessageBox msgBox;
msgBox.setWindowTitle("Error");
msgBox.setText("Please check it.");
msgBox.exec();
quitConn();
setState(POP3_Quit);
}
}
發生以下錯誤:
Invalid parameter passed to C runtime function.
Invalid parameter passed to C runtime function.
ASSERT failure in QWidget: "Widgets must be created in the GUI thread.", file kernel\qwidget.cpp, line 1118
問題似乎是您的smtp_listener
正在另一個線程中執行。 一個相當簡單的Qt解決方案是不嘗試顯示smtp_listener
的錯誤。 而是給您的smtp_listener
一個錯誤信號。 將此信號連接到表格中的插槽,該插槽可顯示錯誤。 Qt的信號系統會將信號排隊,以便在gui線程中執行。
內部類方法內部的錯誤處理不是一個好習慣。
如果您的類smtp_listener
從QObject擴展的,則@Eelke解決方案很好。 但是,如果您具有“清除”類(例如,沒有任何Qt關系,例如來自外部庫),則應引發異常或返回錯誤值 (或表示錯誤狀態的對象)。
該方法為您提供了在一個地方組織錯誤處理的可能性(您的情況下為GUI類)。 對於您和其他讀取您的代碼的程序員來說,這是一個很好的優勢。
順便說一下,您可以使用以下代碼將@Eelke的答案與我的結合起來:
函數返回錯誤:
int smtp_listener::pop3Stat(QString reply)
{
if(reply.contains("+OK"))
{
*t << "stat" <<"\r\n";
t->flush();
setState(POP3_Read);
return 0; // success
}
return 1; // return not null value with error
}
處理錯誤的代碼:
/// slot to handle an error
/// don't forget to connect errorSignal with it
void MainWidnow::errorSignalSlot(int status)
{
QMessageBox::critical(this, "Error", "Error code: " + QString::number(status));
}
void MainWidnow::button_onClick()
{
int status = listener.pop3Stat(reply);
if (status != 0) // not null value means error
{
emit(errorSignal(status)); // emit the signal with error code
}
else
{
qDebug() << "success";
}
}
小部件必須在主線程中創建。 我認為您可以通過信號/插槽或事件將任何消息傳遞到主線程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.