代码之家  ›  专栏  ›  技术社区  ›  Robin Vysloužil

Qt操作无法连接到插槽

  •  1
  • Robin Vysloužil  · 技术社区  · 8 年前

    用c++和qt编写一个学校项目。它应该是一个块编辑器(如draw.io)。我将块生成为按钮并将其设置为网格。每个按钮都应该有自己的菜单,以便能够进行编辑、删除等。(图像示例:

    enter image description here

    我们遇到了一个问题,我们的操作无法连接到插槽。函数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"); 
    }
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   p-a-o-l-o    8 年前

    我想提出一个可能的解释:你把 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 在方法结束时超出范围,因此它将被破坏,连接将丢失其接收器端(即断开)。

    如果实例化 区块项目 对象,使用 ,但意外地将其删除到某个位置。同样,信号发送器 QAction 对象)在接收器中存活,并且连接断开。