简体   繁体   中英

QT: Signal / Slot connection via connect or on_

I am new to QT. As far as I can see, there are two ways to connect signals and slots with each other. One way would be using the connect method. When eg wanting to put a method ButtonReleased() to the slot that is triggered after the released() signal of a pushButton with name pushButton , one could write:

 connect(ui->pushButton, SIGNAL(released()), this, SLOT(ButtonPressed()));

However, as far as I see, one could also define a method with name on_pushButton_released() to achieve the same connection. Is there any difference between both methods and if so, which one is preferred?

Thanks in advance!

There are indeed two main ways to connect signals to slots.

The first one, using the connect method allows to connect any signal to any slot (or signal) as long as the function signatures match. This is the main way to connect signals in Qt.

The second way are member methods that are called on_ObjectName_SignalName() . These are automatically connected by Qt, if a UI element called ObjectName exists and has a signal called SignalName . This is specifically meant for the use case of having some Widget with a separate .ui file, which contains these elements that you want to connect to. As such, this mechanism does not work if you create UI elements "by hand" in your C++ code.

As you can see, the second mechanism has very specific requirements that need to be satisfied to work, although these are not uncommon. So if you have satisfied these conditions I see no Problem in doing it this way, but others may disagree and this is largely personal preference.

Also note: The syntax in your question is the old syntax from Qt4. If you are using Qt5 and newer, it is highly advised to use the new syntax.

You can read more about signals and slots on the Qt Documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM