QT运行出错:QObject::connect: Parentheses expected以及QObject::connect: No such slot ***

时间:2021-02-24 22:59:21

我在QGraphicsScene子类中添加了item的弹出菜单,并连接Action到槽函数,结果槽函数不起作用,输出:QObject::connect: No such slot ***

QT运行出错:QObject::connect: Parentheses expected以及QObject::connect: No such slot ***

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 
//选中item后弹出右键菜单
if (event->button() == Qt::RightButton)
{
    m_pItemSelected = nullptr;
    foreach (QGraphicsItem *item, items(event->scenePos()))
    {
        if (item->type() == QGraphicsPixmapItem::Type)
        {
            m_pItemSelected = item;
            QMenu menu;
            QAction *removeAction = menu.addAction("Remove");
            QAction *toTopLayerAction = menu.addAction("To Top Layer");
            QAction *toBottomLayerAction = menu.addAction("To Bottom Layer");
            QAction *toUpperLayerAction = menu.addAction("To Upper Layer");
            QAction *toLowerLayerAction = menu.addAction("To Lower Layer");
            connect(removeAction, SIGNAL(triggered()), this, SLOT(slotRemoveItem()));
            connect(toTopLayerAction, SIGNAL(triggered()), this, SLOT(slotLayerTop()));
            connect(toBottomLayerAction, SIGNAL(triggered()), this, SLOT(slotLayerBottom()));
            connect(toUpperLayerAction, SIGNAL(triggered()), this, SLOT(slotLayerUpper()));
            connect(toLowerLayerAction, SIGNAL(triggered()), this, SLOT(slotLayerLower()));
            menu.exec(event->screenPos());
            break;
        }
    }
}

在类中使用信号/槽时一定要加Q_OBJECT宏,signal和slots的参数要一样

槽函数加(): connect(toTopLayerAction, SIGNAL(triggered()), this, SLOT(slotLayerTop()));   // 正确

切记忘了():connect(toTopLayerAction, SIGNAL(triggered()), this, SLOT(slotLayerTop));      // 错误