如何从QDialog返回数据?
我正在尝试设计一个主窗口和一个 QDialog,并找到从 QDialog 返回数据的最佳方法。
现在,我正在从对话框捕获 accepted()
信号,然后调用返回数据的对话框函数。还有更好的办法吗?
这是我现在拥有的工作代码:
class MainWindow : public QMainWindow
{
// ...
public slots:
void showDialog()
{
if (!myDialog)
{
myDialog = new Dialog();
connect(myDialog, SIGNAL(accepted()), this, SLOT(GetDialogOutput()));
}
myDialog->show();
}
void GetDialogOutput()
{
bool Opt1, Opt2, Opt3;
myDialog->GetOptions(Opt1, Opt2, Opt3);
DoSomethingWithThoseBooleans (Opt1, Opt2, Opt3);
}
private:
void DoSomethingWithThoseBooleans (bool Opt1, bool Opt2, bool Opt3);
Dialog * myDialog;
};
和对话框:
class Dialog : public QDialog
{
// ...
public:
void GetOptions (bool & Opt1, bool & Opt2, bool & Opt3)
{
Opt1 = ui->checkBox->isChecked();
Opt2 = ui->checkBox_2->isChecked();
Opt3 = ui->checkBox_3->isChecked();
}
};
看起来很乱。有更好的设计吗?我错过了什么吗?
I am trying to design a main window and a QDialog, and to find the best way to return the data from a QDialog
.
Right now I am catching the accepted()
signal from the dialog, after which I call dialog's function that returns the data. Is there any better way?
Here is the working code that I now have:
class MainWindow : public QMainWindow
{
// ...
public slots:
void showDialog()
{
if (!myDialog)
{
myDialog = new Dialog();
connect(myDialog, SIGNAL(accepted()), this, SLOT(GetDialogOutput()));
}
myDialog->show();
}
void GetDialogOutput()
{
bool Opt1, Opt2, Opt3;
myDialog->GetOptions(Opt1, Opt2, Opt3);
DoSomethingWithThoseBooleans (Opt1, Opt2, Opt3);
}
private:
void DoSomethingWithThoseBooleans (bool Opt1, bool Opt2, bool Opt3);
Dialog * myDialog;
};
And the Dialog:
class Dialog : public QDialog
{
// ...
public:
void GetOptions (bool & Opt1, bool & Opt2, bool & Opt3)
{
Opt1 = ui->checkBox->isChecked();
Opt2 = ui->checkBox_2->isChecked();
Opt3 = ui->checkBox_3->isChecked();
}
};
That looks messy. Is there a better design? Am I missing something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我通常这样做:
I usually do this:
这种方式很好,但您也可以考虑让
Dialog
向MainWindow
上的插槽发出一个信号,例如myDialogFinished(bool, bool, bool)
code>,这样就不必在完成后回调Dialog
了。That way is fine, but you could also look at having
Dialog
emit a signal such asmyDialogFinished(bool, bool, bool)
to a slot onMainWindow
, saves having to call back toDialog
after it's finished that way.另一种选择是在完成后向对话框传递一个存储数据的位置。通常,我会在对话框实例化期间执行此操作。
Yet another option is to pass the dialog a place to store the data when it is done. Typically, I would do this during instantiation of the dialog.