mimic
mimic

Reputation: 5224

Qt: two actions in menu (with the same text)

I create a menu dynamically. I add several checkable actions into one menu. Sometimes actions may have the same text that user sees. It's up to user (actually user adds commands into menu).

The problem is in this case clicking works wrong. If I click on the first action (from 2 with the same texts) everything is good but if I click on the second one, both actions are selected. I don't understand why. The code where actions have been created is here:

for (int i = 0; i< currentList.size(); i++)
{
  QString lanKey = currentList.at(i)->Language->toString();  
  QAction* lanAction = new QAction(this);
  QString name ="action_" + currentList.at(i)->Id->toString();
  lanAction->setObjectName(name);
  lanAction->setText(lanKey);
  lanAction->setCheckable(true);
  lanAction->setData(i);
  connect(lanAction, SIGNAL(triggered(bool)), this, SLOT(ShowSomething(bool)));
  ui->menuMy->addAction(lanAction);
}

Here, lanKey is language that may be the same for different actions. Anyway click on the specific action should lead only to checking of this action. What's wrong?

The slot is here:

void VMainWindow::ShowSomething(bool IsTriggered)
{
    QAction* senderAction = (QAction*)sender();
    int listIndex = senderAction->data().toInt();

    if (IsTriggered)
    {

        CreateEditor(subtitles, listIndex);
    }
    else
    {
        //hide this editor
        QString name = "editor" + editorsList->Id->toString();
        QDockWidget* editorDock = this->findChild<QDockWidget*>(name);
        if (editorDock != 0)
        {
            this->removeDockWidget(editorDock);
            this->setLayout(layout());
        }
    }
}

Thanks

The source of problem is found: it turned out that the slot finds the checked action wrong - by text, not by id.

Upvotes: 0

Views: 802

Answers (1)

Tim Meyer
Tim Meyer

Reputation: 12600

I can't find a logical issue in the code you posted so far. Here are a couple of options which I would try in order to resolve this problem:

  1. Limit the users possibilities when adding items to a menu so that he can't add two items with the same name.
  2. Add qDebug() output to ShowSomething to see if there is a problem with signals&slots. For example, if the slot gets called once for the first item but twice for the second item there is a problem there.
  3. Debug into CreateEditor step-by-step.

As the problem seems to appear only for actions with a similar name, you should make sure that you never make a lookup of an action (or something related) by its text() but rather by its data() or objectName() (assuming that currentList.at(i)->Id will always be unique)

Upvotes: 1

Related Questions