用 c++ 和 qt 编写一个学校项目。它应该是一个 block 编辑器(如 draw.io)。我生成 block 作为按钮并将它们设置为网格。每个按钮都应该有自己的菜单,以便能够进行编辑、删除等操作(图片示例:
我们遇到了一个问题,我们的操作无法连接到插槽。函数 akceAkce 应该只在输出上打印 1(通过 qInfo)。但是当我点击菜单按钮时,它什么也没做。任何建议表示赞赏。谢谢!
void BlockItem::createButton() {
this->button = new QPushButton("+");
this->buttonMenu = new QMenu(this->button);
this->connectBlocks = new QAction(tr("Connect"), this->buttonMenu);
connect(this->connectBlocks, &QAction::triggered, this, &BlockItem::akceAkce);
this->buttonMenu->addAction(this->connectBlocks);
this->button->setMenu(this->buttonMenu);
}
void BlockItem::akceAkce() {
qInfo("1");
}
最佳答案
我建议一个可能的解释:您将 BlockItem
实例放在堆栈上,它会超出您代码中某处的范围,并因此被销毁,而按钮、菜单和操作都幸存下来,因为它们是用 new
实例化的,因此它们存在于堆上。
像这样:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
BlockItem blockitem;
blockitem.createButton();
ui->gridLayout->addWidget(blockitem.getButton());
}
在上面的示例代码中,blockitem
在方法结束时超出范围,因此它被销毁并且连接失去其接收方(即中断)。
如果您使用 new
在堆上实例化一个 BlockItem
对象,但不小心将其删除某处,也会发生同样的情况。同样,信号发送方(QAction
对象)在接收方中幸存下来并且连接断开。
关于c++ - Qt Action 不会连接到插槽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50150121/