Important: Please read the Qt Code of Conduct -

Problem with enable method for QPushButton

  • Hi i want to enable button when my text fields are not empty and disable when one or both fields are empty. I tried multiple combinations with logical operators.Any idea how to deal with this

    //by default it is off
    if(userTxt->text()!="" && passTxt->text()!="") //if they are not empty

  • Moderators


    a bit complex of an example, but I wanted everything in main x)

    int main(int argc, char *argv[])
        QApplication a(argc, argv);
        QWidget parent;;
        QLineEdit *edit1 = new QLineEdit;
        QLineEdit *edit2 = new QLineEdit;
        QPushButton *btn = new QPushButton("OK");
        QHBoxLayout *layout = new QHBoxLayout(&parent);
        auto check = [edit1, edit2, btn]()->void{
            btn->setDisabled(edit1->text().isEmpty() || edit2->text().isEmpty());
        QObject::connect(edit1, &QLineEdit::textChanged, [=]()->void{ check();});
        QObject::connect(edit2, &QLineEdit::textChanged, [=]()->void{ check();});
        return  a.exec();

  • Thank you for this.

Log in to reply