4
std::string output; 

if ((checkbox1->isChecked() && checkbox2->isChecked()) && 
   (!checkbox3->isChecked() || !checkbox4->isChecked() || !checkbox5->isChecked() || !checkbox6->isChecked()))
{
  output = " Using Checkbox: 1, 2 ";
}

if ((checkbox1->isChecked() && checkbox2->isChecked() && checkbox3->isChecked()) && 
   (!checkbox4->isChecked() || !checkbox5->isChecked() || !checkbox6->isChecked()))
{
  output = " Using Checkbox: 1, 2, 3 ";
}

....

使用 QT creator 如何验证已检查了多少个复选框并相应地更改输出字符串?有多个 if 语句它不起作用,因为我对所有那些 NOT AND OR 感到困惑。编码所有可能性需要很长时间。

4

4 回答 4

14

你的一切checkBoxes都应该在groupBox

尝试这个:

QList<QCheckBox *> allButtons = ui->groupBox->findChildren<QCheckBox *>();
qDebug() <<allButtons.size();
for(int i = 0; i < allButtons.size(); ++i)
{
    if(allButtons.at(i)->isChecked())
        qDebug() << "Use" << allButtons.at(i)->text()<< i;//or what you need
}
于 2014-09-04T11:03:49.223 回答
2

使用这样的复选框数组

// h-file
#include <vector>
class MyForm {
...
    std::vector< QCheckBox* > m_checkBoxes;
};
// cpp-file
MyForm::MyForm() {
...
    m_checkBoxes.push_back( checkbox1 );
    m_checkBoxes.push_back( checkbox2 );
    ... 
    m_checkBoxes.push_back( checkbox5 );
}
...
    output = " Using Checkbox:";
    for ( int i = 0, size = m_checkBoxes.size(); i < size; ++i ) {
        if ( m_checkBoxes[ i ]->isChecked() ) {
            output += std::to_string( i + 1 ) + ", ";
        }
    }
于 2014-09-04T11:06:50.047 回答
1

TLDR:将它们放在一个容器中并通过迭代它们来构建您的字符串。

代码:

// line taken from @Chernobyl
QList<QCheckBox *> allButtons = ui->groupBox->findChildren<QCheckBox *>();

auto index = 1;
std::ostringstream outputBuffer;
outputBuffer << "Using Checkbox: ";
for(const auto checkBox: allButtons)
{
    if(checkBox->isChecked())
        outputBuffer << index << ", ";
    ++index;
}
auto output = outputBuffer.str();
于 2014-09-04T11:16:27.430 回答
0

使用QString代替std::string然后:

QCheckBox* checkboxes[6];
checkbox[0] = checkbox1;
checkbox[1] = checkbox2;
checkbox[2] = checkbox3;
checkbox[3] = checkbox4;
checkbox[4] = checkbox5;
checkbox[5] = checkbox6;

QStringList usedCheckboxes;
for (int i = 0; i < 6; i++)
{
    if (checkbox[i]->isChecked())
        usedCheckboxes << QString::number(i+1);
}

QString output = " Using Checkbox: " + usedCheckboxes.join(", ") + " ";

这只是一个例子,但有很多方法可以实现它。您可以将复选框保留在QList哪个类字段中,因此您不必checkboxes每次都“构建”数组。当您构建输出等时,您也可以使用字符串QString::arg()代替运算符。+

我提出的只是一个简单的例子。

于 2014-09-04T11:07:09.863 回答