0

I created a .ui file using Qt Designer and in the file I created a PushButton which is disabled initially, I also have a LineEdit. I want to connect LineEdit and PushBotton so that when text changed in LineEdit , the PushButton will be enabled, But I don't find any such option in Signals and slots. Can anyone help?

AAEM
  • 1,837
  • 2
  • 18
  • 26
Madhu Kumar Dadi
  • 695
  • 8
  • 25
  • 1
    connect `textChanged(const QString & text)` with a custom slot that calls `pushButton->setEnabled(true)`. I think you may want also to check `text.isEmpty()` into that slot – Miki Jul 04 '15 at 17:52
  • @Miki I am using Qt 4.8 Designer , I am creating ui files not coding. – Madhu Kumar Dadi Jul 04 '15 at 17:55
  • I'm pretty sure you can / have to write your custom slots... http://stackoverflow.com/questions/7964869/qt-designer-how-to-add-custom-slot-and-code-to-a-button – Miki Jul 04 '15 at 17:56
  • Do you say there is no way we can do it from Designer? – Madhu Kumar Dadi Jul 04 '15 at 17:58
  • I'm saying that I don't think that you have a _standard_ slot that fits your needs, so write your own. You should still be able to connect to that slot in the Designer. – Miki Jul 04 '15 at 18:02
  • Can we add slots to designer? I mean can I create a slot to the Designer? – Madhu Kumar Dadi Jul 04 '15 at 18:03
  • We can create custom slots to the Designer. Check here http://stackoverflow.com/questions/165637/how-do-i-create-a-custom-slot-in-qt4-designer – Madhu Kumar Dadi Jul 04 '15 at 18:18

2 Answers2

4

You have to write a custom slot (which is pretty easy).

Add this to your MainWindow declaration (.h file):

private slots:
    void checkInput(const QString &text);

Your .cpp file:

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(ui->lineEdit, SIGNAL(textChanged(QString)), this, SLOT(checkInput(QString)));
}

void MainWindow::checkInput(const QString &text)
{
    ui->pushButton->setEnabled(!text.isEmpty());
}

To add this slot to Qt Designer, do the following:

  • Right click on your MainWindow, "Change signals/slots";
  • Add your custom slot ("Plus" button) by entering checkInput();
  • After this you will be able to connect your custom slot via Qt Designer.
kefir500
  • 4,184
  • 6
  • 42
  • 48
1

In Qt 5, you generally don't need trivial private slots and should use lambdas instead:

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(ui->lineEdit, &QLineEdit::textChanged, [this](const QString & text) {
      ui->pushButton->setEnabled(!text.isEmpty());
    });
    ...
}
Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313