LineEdit .isEmpty() Problem
-
hello,
i have a lineEdit on My form and i want set a if on it
that when my lineedit are empty my pushButton set disable(true)
and when line edit are not empty my push button set disable(false)
i wrote this codes but not Worked!
what i must to do?if(ui->lineEdit_47->text().isEmpty()){ ui->pushButton_8->setDisabled(true); }else{ ui->pushButton_8->setDisabled(false); }
-
@M4RZB4Ni
The code you wrote is correct. What you need to do is make sure it is connected to a slot. The slot will call a function whenever the lineEdit gets changed and you can check to see if you need to disable or enable the button. Here is some sample code. It has a lineEdit and a button. In the constructor you will do the check to see if you need to enable or disable the button. And then when ever some one changes the text it will call a function and update the state of the button.
Hope this helps out.mainWindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private slots: void on_pushButton_clicked(); void onTextChanged(QString a_strString); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
mainWindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QSettings> #include <QDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); //set slots to see if the line edit has chanegd connect(ui->lineEdit, SIGNAL(textChanged(QString)), this, SLOT(onTextEdited(QString))); if(ui->lineEdit->text().isEmpty()) { qDebug() << "THis works"; ui->pushButton->setDisabled(true); } else { ui->pushButton->setDisabled(false); } } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_clicked() { } void MainWindow::onTextChanged(QString a_strString) { //the text has been edited so you need to see if it is empty if(ui->lineEdit->text().isEmpty()) { ui->pushButton->setDisabled(true); } else { ui->pushButton->setDisabled(false); } }
-
Hi,
A shorter version:
void MainWindow::onTextChanged(const QString &a_strString) { ui->pushButton->setDisabled(a_strString.isEmpty()); }
One some small thing: use a const reference to your QString parameter, that will avoid a useless copy.