問題描述
我已經將 QDialog
子類化以實現類似于 QMessageBox
的功能(我需要它來允許自定義).它有一條短信和確定"、取消"按鈕.我正在使用 exec()
顯示對話框以使其阻塞.現在,當用戶單擊確定/取消時,我如何返回真/假值?
I have subclassed QDialog
to implement functionality similar to QMessageBox
( I needed this to allow for customization). It has a text message and OK, Cancel buttons. I am showing the dialog using exec()
to make it blocking. Now, how do I return values of true/false when the user clicks on OK/Cancel?
我嘗試將按鈕連接到 setResult()
然后,在單擊時返回結果值,但是
I tried connecting the buttons to setResult()
and then, return the result value when clicked, but
- 單擊按鈕不會關閉對話框
- 返回值不正確.以下是我寫的代碼.我認為我在執行/結果部分錯了 - 但我不知道如何解決它.
class MyMessageBox : public QDialog {
Q_OBJECT
private slots:
void onOKButtonClicked() { this->setResult(QDialog::Accepted); }
void onCancelButtonClicked() { this->setResult(QDialog::Rejected); }
public:
MyMessageBox(QMessageBox::Icon icon, const QString& title,
const QString& text, bool showCancelButton = true,
QWidget* parent = 0);
virtual void resizeEvent(QResizeEvent* e);
QDialog::DialogCode showYourself()
{
this->setWindowModality(Qt::ApplicationModal);
this->exec();
return static_cast<QDialog::DialogCode>(this->result());
}
};
用戶將實例化該類并調用 showYourself()
,它應該返回值并關閉(和刪除)對話框.
The user will instantiate the class and call showYourself()
which is expected to return the value and also close(and delete) the dialog.
我已經發布了部分代碼.如果您需要更多,請告訴我,我會發布完整版本.
I have posted partial code. Let me know if you need more and I will post the complete version.
推薦答案
幾點:
- 與其自己使用
setResult()
,不如使用 QDialog::accept() 和 QDialog::r??eject(). - 看來您沒有充分利用信號和插槽.您需要創建對話(或另一個)的對象來收聽對話的信號.
- 在您的代碼中,您也沒有將信號連接到插槽.
- 在我的修復中
onOKButtonClicked
和onCancelButtonClicked
是不必要的. - 通過我的修復,您不需要
showYourself()
.只需調用exec
和事件信息會流動.
- Rather than using
setResult()
yourself, use QDialog::accept() and QDialog::reject(). - It seems you are not taking full advantage of the signals and slots. You need the object which create the dialog (or another one) to listen to the signals of the dialog.
- In your code you are not connecting signals to slots either.
- With my fix
onOKButtonClicked
andonCancelButtonClicked
are unnecessary. - With my fix you don't need
showYourself()
. Just callexec
and with the events information will flow.
您需要在顯示對話框之前添加此代碼(this
假設它在對話框方法中):
You need to add this code before showing the dialog (this
assume it is in a dialog method):
QObject::connect(acceptButton, SIGNAL(clicked()), this, SLOT(accept()));
QObject::connect(rejectButton, SIGNAL(clicked()), this, SLOT(reject()));
在調用者對象中你有
void someInitFunctionOrConstructor(){
QObject::connect(mydialog, SIGNAL(finished (int)), this, SLOT(dialogIsFinished(int)));
}
void dialogIsFinished(int){ //this is a slot
if(result == QDialog::Accepted){
//do something
return
}
//do another thing
}
這篇關于QDialog exec() 并獲取結果值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!