Qt connecting signals and slots
-
14-07-2021 - |
Question
In my Qt project I've a QPushButton
and a QLineEdit
instances. And I want to set QLineEdit disabled when QPushButton is pressed.
I've written this code:
this->btn = new QPushButton(this);
this->txt = new QLineEdit(this);
QObject::connect(this->btn,SIGNAL(clicked(bool)),this->txt,SLOT(setDisabled(bool)));
which doesn't work. Can you help me please? What is my mistake?
Solution
The clicked(bool)
signal is always false
for non-checkable buttons. It will never emit true
unless you set setCheckable(true)
, in which case it emits true
when you check it, and false
when you uncheck it. Non-checkable buttons cannot be checked (obviously), which is why the signal always emits false
.
So in this case, simply provide your own slot where you manually toggle between setDisabled(true)
and setDisabled(false)
. Or make the button checkable first with setCheckable(true)
(it might even be more suitable in this case; just test it and see.)
OTHER TIPS
QLineEdit
does not have a method setDisabled
according to the documentation
Try setReadOnly
instead.