Important: Please read the Qt Code of Conduct -

Whats the best solution?

  • I'm looking at some old code which tests for a single character in a QString, currently there are a lot if else tests with a single line in the body of the if:

        if ( strSymbol== "~" ) {
            ui->lnedField->setText(ui->text() + "~");
        } else if ( strSymbol == "!") {
            ui->lnedField->setText(ui->text() + "!");
        } ....

    There is a total of about 40 if else's, is it more efficient to do this or to create a single array (string) of all characters to test then use:

        QString strChList = "~!@#$%^& ....
        if ( strChList.indexOf(strTest) != -1 ) {
            QString strCurrent(ui->lnedField->text());

    Or is there another more optimal solution?

  • Lifetime Qt Champion

    @SPlatten Sounds like a good idea, but make strChList const static

  • @jsulm, Thank you

    On looking into this a it further its not quite as straight forward as I first thought....because the destination is a QLineEdit, we first have to get the content of the QLineEdit, unfortunately QLineEdit has no append function.

Log in to reply