Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this slot get called twice?

Tags:

c++

qt4

qmenubar

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 ?

like image 707
pintoch Avatar asked May 06 '12 19:05

pintoch


2 Answers

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

like image 79
rlnunes Avatar answered Sep 20 '22 03:09

rlnunes


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.

like image 22
Arnold Spence Avatar answered Sep 19 '22 03:09

Arnold Spence