2

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.

Vasundhara Mehta
  • 278
  • 2
  • 3
  • 16

3 Answers3

1

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 ());
Mattia F.
  • 1,720
  • 11
  • 21
  • Can I pass the label as an argument in the custom slot? I believe QT signals and slots need to have the same number of arguments, but i need to connect a particular label with a particular textbox and they are created dynamically by the user at runtime, hence I cannot keep a reference to it in my class. – Vasundhara Mehta Jul 04 '16 at 14:24
0
  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.
ilotXXI
  • 1,075
  • 7
  • 9
0

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); });
majk
  • 827
  • 5
  • 12