I have the following piece of code, for some reason, from the UI window, MyActionDock inherited from QToolBar, it is displayed without any problem, when clicked on the button, the button color also changed, but the slots (a1ActionSlot(), and a2ActionSlot()) connected to the signals are never called, feel like the action is never triggered. I'm using Qt 4.7.2. What's wrong with it? Thanks a lot.

I believe the code used to work properly for Qt4.6 or earlier. Don't know when the problem happens.

MyActionDock::MyActionDock (QWidget *parent) :
   QToolBar (parent)
{
   setOrientation (Qt::Vertical);
   setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
   setFixedWidth(canvas()->toolsDockWidth());

   // ACTIONS

   QToolButton * a1btn= new QToolButton (this);

   a1btn->setText("Action 1");
   a1btn->setIcon(QIcon("a1.png"));
   a1btn->setToolTip ("Some action a1");
   a1btn->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);

   QAction *a1Action = addWidget(a1btn);
   connect (a1Action , SIGNAL (triggered()), this, SLOT(a1ActionSlot()));
   addAction (a1Action);

   QToolButton * a2Btn = new QToolButton (this);

   a2Btn ->setText("A2");
   a2Btn ->setIcon(QIcon("a2.png"));
   a2Btn ->setToolTip ("something");

   QAction *a2Action= addWidget(a2Btn );
   connect (a2Action, SIGNAL (triggered()), this, SLOT(a2ActionSlot()));
   addAction (a2Action);

}

void MyActionDock::a1ActionSlot()
{
    //do something
}

void MyActionDock::a2ActionSlot()
{
   //do something
}
有帮助吗?

解决方案

As Jay suggested, directly connect to the QToolButton and don't addAction, then it works. Think this is a Qt upgrade related problem. The code used to work in Qt 4.6 or earlier, but it stopped working after 4.7. So for 4.7 if you want to use QToolButton, direct connect the button's signal.

   QToolButton * a2Btn = new QToolButton (this);

   a2Btn ->setText("A2");
   a2Btn ->setIcon(QIcon("a2.png"));
   a2Btn ->setToolTip ("something");

   addWidget(a2Btn );
   connect (a2Btn , SIGNAL (clicked()), this, SLOT(a2ActionSlot()));

其他提示

The slot is in the wrong class.

You declare the slot a1ActionSlot is in the class MyActionDock here:

connect (a1Action , SIGNAL (triggered()), this, SLOT(a1ActionSlot()));

The third parameter is 'this' (which points to the MyActionDock class).

You instantiate the a1ActionSlot method in the class QtCanvasActionDock.

void QtCanvasActionDock::a1ActionSlot()
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top