Search code examples
qtqtguiqlineedit

QLineedit disabling/re-enabling.


I have an equation with four variables, only 3 need to be defined for the program to run. When 3 of the parameters have been defined (via lineedits in my GUI) I'd like the fourth to be greyed out. I only know how to link two parameters at the moment by disabling one lineedit when another is edited. e.g.

void WaveformGen::on_samples_textEdited(const QString &arg1)
{
    ui->cycles->setDisabled(true);
}

So when samples is edited I disable another lineedit called cycles


Solution

  • Using one single slot:

    class WaveformGen {
    private:
        QList<QLineEdit *> m_lineEdits;
    private slots:
        void lineEditTextEdited(const QString &text);
        ...
    };
    
    WaveformGen::WaveformGen()
    {
        ...
        // create an ordered list of line edits:
        m_lineEdits << ui->lineEdit1 << ui->lineEdit2 << ui->lineEdit3 << ui->lineEdit4;
        // connect all to same slot:
        foreach(QLineEdit *lineEdit, m_lineEdits) {
            connect(lineEdit, SIGNAL(textEdited(const QString &)), this, SLOT(lineEditTextEdited(const QString &)));
        }
    }
    
    void WaveformGen::lineEditTextEdited(const QString &str)
    {
        // iterate over all lineEdits:
        for (int i = 0; i < m_lineEdits.count() - 1; ++i) {
            // enable the next lineEdit if the previous one has some text and not disabled
            m_lineEdits.at(i+1)->setEnabled(!m_lineEdits.at(i)->text().isEmpty() && m_lineEdits.at(i)->isEnabled());
        }
    }