Why is this slot called twice?

My problem is that when I click on an item in a QMenuBar, the corresponding slot is called twice. I am using Qt 4.8.1. I do not use Qt Designer or the auto-join 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 will see that clicking on “Click here” will print “Trigger” once and “Or here” twice. I do not understand why.

What am I doing wrong?

+5
source share
2 answers

I get the same incorrect result as on Windows 7 x64 using Qt 4.8.1. It certainly seems like a mistake.

​​ , Mac OS X. , , Windows 7.

, .

+2

Qt::UniqueConnection :

connect(menu, SIGNAL(triggered(QAction*)), this, SLOT(handleAction(QAction*)), Qt::UniqueConnection);

http://doc.qt.io/qt-4.8/qt.html#ConnectionType-enum

+4

All Articles