My problem is that when I click on an item in a QMenuBar, the corresponding slot gets called twice. I'm using Qt 4.8.1. I'm not using Qt Designer nor the "auto-connection" feature. Here is my code snippet :
#include <iostream>
#include <QWidget>
#include <QMenuBar>
class MyWidget : public QWidget
{
Q_OBJECT
public:
MyWidget(QWidget *parent = 0) : QWidget(parent)
{
QMenuBar *menu = new QMenuBar(this);
menu->addAction("Click here");
menu->addAction("Or here");
connect(menu, SIGNAL(triggered(QAction*)), this, SLOT(handleAction(QAction*)));
}
public slots:
void handleAction(QAction *action)
{
std::cout << "Triggered" << std::endl;
}
};
And the main function :
#include "main.h"
#include <QApplication>
int main(int argc, char **argv)
{
QApplication app(argc, argv);
MyWidget w;
w.show();
return app.exec();
}
If you compile this (with the MOC file), you'll see that clicking on "Click here" will print "Triggered" once, and "Or here" twice. I don't understand why.
What am I doing wrong ?
Use Qt::UniqueConnection
to solve:
connect(menu, SIGNAL(triggered(QAction*)), this, SLOT(handleAction(QAction*)), Qt::UniqueConnection);
http://doc.qt.io/qt-4.8/qt.html#ConnectionType-enum
I get the same incorrect result as you on Windows 7 x64 using Qt 4.8.1. This certainly seems like a bug.
There was a bug reported and fixed for what appears to be the same behavior on Mac OS X. Although it has been closed, there is a single comment on it that they observed this problem on Windows 7.
I think filing a new bug report would be a good idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With