0

I was playing around with the Qt demo browser example mentioned here and noticed an anomaly when I tried making a minor change to the bookmark handling code.

My intention was to make the bookmarks in the toolbar open up in a new tab instead of the existing tab. It works perfectly for the bookmarks that are located directly on the bookmarks tab. But the bookmarks inside a folder are the ones which are behaving weirdly.

I modified the BookmarksToolBar::activated SLOT in the bookmarks.cpp to open the url in a new tab instead of existing tab. That's when I noticed that the SLOT is being called multiple times, the count being equal to the number of times the menu is rendered. i.e, the first time a menu item is activated, the SLOT is called once, the next time an item is activated, the SLOT gets called twice and so on.

I thought there must have been multiple signal-slot connections and thus I checked on the BookmarksToolBar::build() method where the signal-slot connection is done and found that the control flow enters the method only once. I am finding it hard to figure out how the SLOT is being called multiple times.

The project is question is an example project 'Tab browser' which comes with Qt and can be accessed by clicking on 'Examples' on the Qt-Creator welcome screen. Thus I did not post any source code here.

Any guidance or help in understanding the cause for this anomaly and possible solutions to fix it would be appreciated.

Nithish
  • 1,580
  • 12
  • 21

1 Answers1

1

Found the cause of the problem and solution myself. The root of the problem is in modelmenu.cpp.

Apparently the ModelMenu::createMenu method connects the QMenu::triggered and QMenu::hovered signals to SLOT each time the method is called. The SLOT triggered emits the signal ModelMenu::activated.

Using Qt::UniqueConnection should solve the issue.

Replacing this:

connect(menu, SIGNAL(triggered(QAction*)), this, SLOT(triggered(QAction*)));
connect(menu, SIGNAL(hovered(QAction*)), this, SLOT(hovered(QAction*)));

With this:

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

Fixed the problem. Just leaving this here hoping this would help someone in future.

Nithish
  • 1,580
  • 12
  • 21
  • 1
    Qt has UniqueConnection connect type for precisely this case - http://doc.qt.io/qt-4.8/qt.html#ConnectionType-enum – Shf Jan 19 '16 at 12:49
  • @Shf: So stupid of me. Setting the connection type did not come to my mind. Thank you. – Nithish Jan 19 '16 at 12:51