QT signal slot connection method

Qt::DirectConnection

Assuming that there are currently 4 slots connected to QPushButton::clicked(bool), when the button is pressed, QT will call these 4 slots in the order of connection time. Obviously this way cannot cross threads (pass messages).

Qt::QueuedConnection

Assuming that there are currently 4 slots connected to QPushButton::clicked(bool), when the button is pressed, QT wraps the signal into a QEvent and puts it in the message queue. QApplication::exec() or the thread's QThread::exec() will fetch the message from the message queue and call several slots associated with the signal. This way you can pass messages both within threads and across threads.

Qt::BlockingQueuedConnection

Similar to Qt::QueuedConnection, but blocks until all associated slots are executed. The word blocking appears here, indicating that it is specifically used to pass messages between multiple threads.

Qt::AutoConnection

This connection type automatically selects Qt::DirectConnection or Qt::QueuedConnection depending on whether signal and slot are in the same thread

In this way, the efficiency of the first type is definitely higher than that of the second type. After all, the second method needs to store messages in the queue, and may involve the copying of large objects (consider sig_produced(BigObject bo), bo needs to be copied to in the queue).

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    
    
    ui->setupUi(this);
    bool ret1=connect(ui->pushButton,&QPushButton::clicked,this,&MainWindow::Deal_clicked,Qt::AutoConnection);
    cout<<"ret1="<<ret1<<endl;

    bool ret2=connect(ui->pushButton,&QPushButton::clicked,this,&MainWindow::Deal_clicked,Qt::AutoConnection);
    cout<<"ret2="<<ret2<<endl;
    emit ui->pushButton->clicked();

}
void MainWindow::Deal_clicked()
{
    
    
    cout<<"Deal_clicked"<<endl;

}

输出:
ret1=1
ret2=1
Deal_clicked
Deal_clicked

Qt::UniqueConnection
When Qt::UniqueConnection is set, QObject::connect() will fail if the connection already exists (ie, if the same signal is already connected to the same slot on the same pair of objects).

bool ret1=connect(ui->pushButton,&QPushButton::clicked,this,&MainWindow::Deal_clicked,Qt::UniqueConnection);
    cout<<"ret1="<<ret1<<endl;
    
 bool ret2=connect(ui->pushButton,&QPushButton::clicked,this,&MainWindow::Deal_clicked,Qt::UniqueConnection);
    cout<<"ret2="<<ret2<<endl;
 emit ui->pushButton->clicked();

输出:
ret1=1
ret2=0
Deal_clicked
可以看出第二次连接失败了

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324125578&siteId=291194637