Can't use Qt::UniqueConnection in Qt Connect

372 Views Asked by At

I have a connect statement that compiles fine, with the connection type QueuedConnection. Once I OR it with UniqueConnection, it refuses to compile. I had to re-cast it back to Qt::ConnectionType for it to run. Is this normal/expected behaviour?

I thought the connection method definition would accept an int (which is equivalent to enum) without complaint.

connect(
    mySource, SIGNAL(mySig()),
    this, SLOT(mySlot())),
    static_cast<Qt::ConnectionType> 
    (Qt::QueuedConnection|Qt::UniqueConnection));
2

There are 2 best solutions below

3
On

I try this Example :

QPushButton *button = new QPushButton();
button->setText("Clicke me ");
ui->gridLayout->addWidget(button);

connect(button,&QPushButton::clicked,this,[](){
qDebug()<<"button is clicked";
}, Qt::UniqueConnection);

what you write In your connect is wrong, because you should follow this style :

connect(object,SIGNAL(mySig()), this,SLOT(mySlot())),Qt::QueuedConnection); 

you can't use two Connections at the same time

enter image description here

From Qt::ConnectionType for Qt::UniqueConnection :

This is a flag that can be combined with any one of the above connection types, using a bitwise OR. When Qt::UniqueConnection is set, QObject::connect() will fail if the connection already exists (i.e. if the same signal is already connected to the same slot for the same pair of objects). This flag was introduced in Qt 4.6.

Noted that it was introduced in Qt 4.6 and it said that if the connection already exists QObject::connect() will fail.

as I try

  connect(button,&QPushButton::clicked,this,[](){
    qDebug()<<"button is clicked";
    }, Qt::UniqueConnection or Qt::QueuedConnection);

I got an error too because I use the Qt 6 version and it may work in Qt 4.6.

From https://stackoverflow.com/a/20717599/9484913 I try this :

QPushButton *button = new QPushButton();
button->setText("Clicke me ");
ui->gridLayout->addWidget(button);

QObject::connect(button,&QPushButton::clicked,this,[](){
qDebug()<<"button is clicked";
}, static_cast<Qt::ConnectionType>(Qt::QueuedConnection | Qt::UniqueConnection));

and it works:

enter image description here

1
On

You have to explicitly choose one of the connection types, you cannot have multiple in one connection.

Check the doc for their differences: Qt connections types