Solved Where did the signals go when I triggered them from the ui?
-
I'm getting confuse. I have a lineEdit and a plainTextEdit, and I want to trigger a search function when I hit "enter" on the lineEdit. I can do that in the ui by choosing "returnPressed()" as the signal, but where is this signal and the connect call in the cpp?
Only the slot was generated with the name "on_xxx_returnPressed" in the cpp and header file, is this an implicit format required for the magic to happen? I want the name of the slot to be more meaningful, but when I changed it, the magic goes away.
-
@lansing thats a feature of QMetaObject::connectSlotsByName
if you don't want to rely on the auto connection by function name, you'll have to do a QObject::connect declaration yourself.
take a look at the QObject docu page, should get you started nicely.
-
The "magic" happens in QMetaObject::connectSlotsByName which is awful because, as you noticed already, it breaks really fast.
You can add your own connect in the constructor after the
setupUi()
call:connect(ui->lineEdit,&QLineEdit::returnPressed,this,&MyClass::mySlot);
-
Ok thank you guys, that solved the mystery for me. I have watched tutorials on Youtube and they're all teaching this black box magic, but on the project I work on, they don't do it like that.
Also good to learn that I can reference any existing signal in the connect call.
-
@lansing Qt's Signal/Slot mechanismn is much more powerful than one would think.
its a save way to pass data between threads, you can even forgo the Slot all together and connect a signal direct to a lambda.
Signals and Slots can individually(manualy) be called from your code, etc.
QByteArray page = ...; QTcpSocket *socket = new QTcpSocket; socket->connectToHost("qt-project.org", 80); QObject::connect(socket, &QTcpSocket::connected, [=] () { socket->write("GET " + page + "\r\n"); });
-
Why sometime they use SIGNAL() and SLOT() and sometime they use "&" in the argument?
-
@lansing the Syntax changed from Qt4 to Qt5, for compatibility reasons, you can still use both, but it is recommanded to use the new QT5 version with the function pointers.
Take a look here:
http://doc.qt.io/qt-5/signalsandslots.html
and here
https://wiki.qt.io/New_Signal_Slot_Syntax -
Okay got it, so the "&" is the newer way.
-
@lansing
Yes its the so called new syntax even not so new anymore.
https://wiki.qt.io/New_Signal_Slot_SyntaxIts highly recommended to use this syntax as it fails at compile time if something is wrong.
the SIGNAL()/SLOT() fails at runtime.Also QMetaObject::connectSlotsByName as mentioned should only be used for test code
as it breaks so easy if someone renames a widget or rename the slot.
And it first show when app runs, making it a truly no go for production code as
that is very unwanted in terms of support and debugging.