Search code examples
qtqcombobox

Check if text from ComboBox is the same has other ComboBox


I have 8 ComboBoxes with the tag as channel_1 ... channel_8.

I want to check if the user chooses the same option in 2 of them, except the first option which is 'none'.

I've created this slot but the final_a and final_b variables created are not recognized.

// Slot to check if there's two channels with the same option choosed
void gui::check_channels_options()
{
    for (int a = 1; a <= 8; a++)
    {
        for (int b = 1; b <= 8; b++)
        {
            if(a != b)
            {
                QString A, B;
                A.setNum(a);
                B.setNum(b);

                QString Na, Nb;
                Na = "channel_";
                Na += A;
                Nb = "channel_";
                Nb += B;

                QByteArray bytes_a = Na.toAscii();
                char* final_a = bytes_a.data();

                QByteArray bytes_b = Nb.toAscii();
                char* final_b = bytes_b.data();

                if((ui->final_a->currentText() == ui->final_b->currentText()) &&
                        (ui->final_a->currentIndex() != 0 && ui->fnal_b->currentIndex() != 0))
                {
                    QMessageBox::warning(this,"Error","Channel " + a + " has the same option as channel " + b,QMessageBox::Ok);
                }

                else
                {

                }
            }     
        }
    }
}

can anyone help me?


Solution

  • You are declaring final_a and final_b on the stack, but then referring to them as ui->final_a and ui->final_b. Try removing the "ui->" from those.

    In general, I think your approach could be simplified, though. For example, say you have pointers to your combo boxes stored in an array called comboBoxes. Then you can just do this:

    // create the combo boxes somewhere in your program, perhaps like this:
    QComboBox *comboBoxes[8];
    for (int i = 0; i < 8; ++i)
    {
        comboBoxes[i] = new QComboBox;
    }
    
    // Slot to check if there's two channels with the same option choosed
    void gui::check_channels_options()
    {
        for (int a = 0; a < 8; ++a)
        {
            for (int b = 0; b < 8; ++b)
            {
                if (a == b ||
                    comboBoxes[a]->currentText() == "none" ||
                    comboBoxes[b]->currentText() == "none")
                    continue; // no need to test these for equality
                else if (comboBoxes[a]->currentText() == comboBoxes[b]->currentText)
                    // issue warning
                else
                    // they are OK
            }
        }
    }