【发布时间】:2016-09-02 20:20:38
【问题描述】:
如何从QDialog 返回自定义值?它是documented 它返回
QDialog::Accepted 1
QDialog::Rejected 0
如果用户分别按Ok 或Cancel。
我正在考虑一个自定义对话框,即三个复选框以允许用户选择一些选项。 QDialog 适合这个吗?
【问题讨论】:
如何从QDialog 返回自定义值?它是documented 它返回
QDialog::Accepted 1
QDialog::Rejected 0
如果用户分别按Ok 或Cancel。
我正在考虑一个自定义对话框,即三个复选框以允许用户选择一些选项。 QDialog 适合这个吗?
【问题讨论】:
您将对 2 个功能感兴趣:
QDialog::setResult() 允许您使用任何整数作为返回值(无需关闭对话框):http://doc.qt.io/qt-5/qdialog.html#setResult。QDialog::done() 做同样的事情,除了它关闭对话框并使QDialog::exec() 返回您指定的结果:http://doc.qt.io/qt-5/qdialog.html#done
通常,QDialog 中的“确定”按钮连接到QDialog::accept() 插槽。你想避免这种情况。相反,编写您自己的处理程序来设置返回值:
// Custom dialog's constructor
MyDialog::MyDialog(QWidget *parent = nullptr) : QDialog(parent)
{
// Initialize member variable widgets
m_okButton = new QPushButton("OK", this);
m_checkBox1 = new QCheckBox("Option 1", this);
m_checkBox2 = new QCheckBox("Option 2", this);
m_checkBox3 = new QCheckBox("Option 3", this);
// Connect your "OK" button to your custom signal handler
connect(m_okButton, &QPushButton::clicked, [=]
{
int result = 0;
if (m_checkBox1->isChecked()) {
// Update result
}
// Test other checkboxes and update the result accordingly
// ...
// The following line closes the dialog and sets its return value
this->done(result);
});
// ...
}
【讨论】:
QWidget *parent = nullptr 是当前的Qt 推荐方法还是当前的 C++ (C++14?) 趋势(我通常这样做/看到 QWidget *parent = 0)?
parent = 0 是旧样式。 C++11引入了nullptr,所以现在写parent = nullptr比较好。