【问题标题】:QDialog return value, Accepted or Rejected only?QDialog 返回值,仅接受还是拒绝?
【发布时间】:2016-09-02 20:20:38
【问题描述】:

如何从QDialog 返回自定义值?它是documented 它返回

QDialog::Accepted   1
QDialog::Rejected   0

如果用户分别按OkCancel

我正在考虑一个自定义对话框,即三个复选框以允许用户选择一些选项。 QDialog 适合这个吗?

【问题讨论】:

    标签: c++ qt qt5 c++14 qdialog


    【解决方案1】:

    您将对 2 个功能感兴趣:

    通常,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);            
        });
    
        // ...
    }
    

    【讨论】:

    • 虽然这是可能的,但我通常只是让复选框值可以通过 getter 访问,并在 exec() 返回 Accepted 时调用它们。这样可以减少代码,并且也往往更具可读性。
    • @JKSH,我正在考虑如何将复选框选择的组合编码为整数。但遵循 Frank Osterfeld 的想法似乎有助于避免这种努力,这可能是一件好事。
    • 附带问题,QWidget *parent = nullptr 是当前的Qt 推荐方法还是当前的 C++ (C++14?) 趋势(我通常这样做/看到 QWidget *parent = 0)?
    • 同意,@FrankOsterfeld 的方法更简洁。
    • @KcFnMi parent = 0 是旧样式。 C++11引入了nullptr,所以现在写parent = nullptr比较好。
    猜你喜欢
    • 1970-01-01
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多