QT signal and slot overloading problems and solutions

        Introduction: I recently learned QT and encountered the problem of signal and slot function overloading when using signals and slots. After learning and understanding, I have found the following ways to solve it:

         The expression of connect function in QT:

QT4 and below versions:

QObject::connect(const QObject *sender,const char *signal,const QObject *recevier,const char *method,QT::ConnectionType type=Qt::Auto)   

Example: Use the connect() function to associate the clicked() signal function of the Button with the close() slot function of the widget window. The implementation code is as follows

connect(&But,SIGNAL(clicked()),&widget,SLOT(close()));

Note:Character based matching

QT5 and above

QObject::connect(const QObject *sender, PointerToMemberFunction signal, const QObject *receiver, PointerToMemberFunction method, Qt::ConnectionType type = Qt::AutoConnection)

For example, use the new connect() function to associate the clicked() signal function of the Button and the close() slot function of the widget window. The implementation code is:

connect(&But, &QPushButton::clicked, &widget, &QWidget::close);

Note: Matching based on method address

When a signal or slot function is overloaded

1. You can use the QT4 form directly, and the function has been clearly used in its expression form, and there is no ambiguity caused by overloading.

2. For QT5 and above expressions, you can use the following two methods to solve the problem:

a. Use static_cast to force type conversion of the corresponding signal or slot function:

       Syntax format: static_cast <type-id>( expression )

For example, use the connect function to associate the timeout() function of the timer with the update() slot function of the MainWindow window.

 connect(&timer,&QTimer::timeout,&MainWindow,static_cast<void (MainWindow::*)()>(&QMainWindow::update));

b. Use function pointer form to implement;

For example, use the connect function to associate the timeout() function of the timer with the update() slot function of the MainWindow window.

void (MainWindow::*update_01)()=&QMainWindow::update;
connect ( & timer , & QTimer :: timeout , & MainWindow , update_01 );

Note: The above is based on personal learning and understanding. Corrections and exchanges are welcome.

Guess you like

Origin blog.csdn.net/hubery_Block/article/details/122058169