首页 > 解决方案 > QT-信号和插槽 setEnabled(bool) 插槽不起作用

问题描述

我一直在使用 开发一个简单的记事本应用程序QT,目前被困在一个我必须禁用的地方,actionUndo并且actionRedo当撤消或重做分别不适用时。我使用了 的连接方法QT,目前我的constructor function(连同includes)看起来像这样:

#include "notepad.h"
#include "ui_notepad.h"
#include "about.h"
#include <QFile>
#include <QTextStream>
#include <QFileDialog>
#include <QIcon>
#include <QFont>
#include <QFontDialog>
#include <QTextCursor>

Notepad::Notepad(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Notepad)
{
    ui->setupUi(this);
    setWindowTitle("QNotepad");
    setWindowIcon(QIcon(":/icons/icons/qnotepad.png"));
    setCentralWidget(ui->textBody);

    //Enabling the options, only when applicable
    connect(ui->textBody, SIGNAL(undoAvailable(bool)), ui->actionUndo, SLOT(setEnabled(bool)));
    connect(ui->textBody, SIGNAL(redoAvailable(bool)), ui->actionRedo, SLOT(setEnabled(bool)));

}

完整的来源在这里

但似乎它不起作用,因为当我运行程序时,即使没有可用的撤消和重做操作, actionUndoand仍保持启用状态。actionRedo

问题截图

我使用 Arch Linux 作为主要开发环境

标签: c++qt

解决方案


Qt Ui 元素(小部件、操作等)默认启用,因此您需要在您的 notepad.ui 文件的 Qt 设计器的属性窗口中取消选中 Undo 和 Redo 操作的启用标志。或者,您可以在窗口的构造函数中执行此操作,如下所示:

ui->actionUndo->setEnabled(false);
ui->actionRedo->setEnabled(false);

//Enabling the options, only when applicable
connect(ui->textBody, &QTextEdit::undoAvailable, ui->actionUndo, &QAction::setEnabled);
connect(ui->textBody, &QTextEdit::undoAvailable, ui->actionRedo, &QAction::setEnabled);

这样,只有在 QTextEdit 发出信号时,它们才会打开/关闭。

还可以考虑对信号/插槽连接使用仿函数语法,如我截取的代码所示,因为它有几个优点。请参阅此处了解更多信息。


推荐阅读