简体   繁体   English

Qt操作将无法连接到插槽

[英]Qt action won't connect to slot

Writing a school project in c++ and qt. 用c ++和qt编写学校项目。 It is supposed to be a block editor (like draw.io). 它应该是一个块编辑器(如draw.io)。 I generate blocks as a buttons and setting them to a grid. 我将块生成为按钮并将其设置为网格。 Each button is supposed to have own menu to be able to get edited, deleted, etc. (image example: 每个按钮都应该具有自己的菜单,以便能够进行编辑,删除等操作(图片示例:

在此处输入图片说明

We are encountering a problem, that our action won't connect to a slot. 我们遇到问题,我们的操作无法连接到插槽。 Function akceAkce is supposed only to print 1 onto output (via qInfo). 假定函数akceAkce仅将1打印到输出(通过qInfo)。 But when I click on the menu button, it does nothing. 但是,当我单击菜单按钮时,它什么也没做。 Any suggestions appreciated. 任何建议表示赞赏。 Thanks! 谢谢!

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"); 
}

I would suggest a possible explanation: you put the BlockItem instance on the stack, and it's going out of scope somewhere in your code, and destroyed consequently, while the push button, menu and action all survive it, since they're instantiated with new , thus they live on the heap. 我建议一个可能的解释:将BlockItem实例放到堆栈上,它超出了代码范围,然后销毁了它,而按钮,菜单和操作全部都保留了下来,因为它们是用new实例化的。 ,因此它们生活在堆中。

Something like this: 像这样:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    BlockItem blockitem;
    blockitem.createButton();

    ui->gridLayout->addWidget(blockitem.getButton());
}

In the sample code above, blockitem goes out of scope at the end of the method, so it is destroyed and the connection loses its receiver side (ie breaks). 在上面的示例代码中,方法结束时, blockitem超出了范围,因此它被破坏了,连接丢失了接收方(即中断)。

The same would happen if you instantiate a BlockItem object on the heap, using new , but accidentally delete it somewhere. 如果您使用new实例化堆上的BlockItem对象,但意外地将其删除,则会发生同样的情况。 Again, the signal sender (the QAction object) survives the receiver and the connection is broken. 同样,信号发送器( QAction对象)在接收器中幸存下来,并且连接断开。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM