2
votes

I have a QLineEdit which I Want to connect to a QLabel so that depending on the validity of the text entered. I have two problems while doing this.

QLineEdit *text = new QLineEdit(this);
layout->addWidget(text, rowno, 0);
QLabel *button = new QLabel(this);
button->setStyleSheet("QLabel { background-color : green; color : white; }");
button->setAlignment(Qt::AlignCenter);
button->setText("OKAY");
QObject::connect(text, SIGNAL(textEdited(const QString &)), button, SLOT(CheckValidity(const QString &)));

this does not connect any changes made in QLineEdit to my custom slot. I cannot figure out why! Also in the custom slot, I want to change the background colour of my label depending on the QString passed. How do I get a reference for the label? It is present as the receiver of the signal but I can't figure out a way to refer to it.

3

3 Answers

1
votes

CheckValidity is not a QButton's slot, it's a custom slot defined in your own class (I assume that, since you have not specified it).

So, change the last line to:

QObject::connect(text, SIGNAL(textEdited(const QString &)), this, SLOT(CheckValidity(const QString &)));

If you want to know the sender object, use qobject_cast:

QLabel *sender_label = qobject_cast<QLabel*> (sender ());
0
votes
  1. There is no CheckValidity slot in QLabel (why button is QLabel?). Check output window of debugger after connection trying.
  2. QObject::sender() + cast. Cast may be dynamic_cast or qobject_cast, look their difference in Qt Assistant.
0
votes

If you want to supply additional arguments into your slot invocation, you can use lambda instead of a slot:

QObject::connect(text, &QLineEdit::textEdited, [=](const QString &text) { checkValidity(button, text); });