在Qt中实现退出按钮

Implementing Exit button in Qt

我正在尝试实现退出按钮,但我无法使用 connect() 方法来执行此操作。事实上,据我所知,我的按钮没有发出任何信号,但我找不到问题所在。 这是我使用 connect() 方法的部分代码:

#include "MyMainWindow.h"

MyMainWindow::MyMainWindow(QWidget * parent, Qt::WindowFlags flag) :
        QMainWindow(parent, flag)
{
    this->setFixedSize(1120, 630);
    menu = new MyMenu(this);
    this->setCentralWidget(menu);
    this->show();
    // the connect implementation
    connect(menu->exit, SIGNAL(clicked()), this, SLOT(this->exit_button_clicked()));
}

MyMainWindow::~MyMainWindow()
{
}

void MyMainWindow::exit_button_clicked()
{
    this->close();
}

MyMainWindowMyMenu 的朋友 class,exit 是私人 QPushButton。现在我需要一些帮助来解决这个问题。

您可以直接如下使用

connect(menu->exit, SIGNAL(clicked()), this, SLOT(close()));

不需要创建新方法 exit_button_clicked() 作为 SLOT

SLOT 是一个实际上接受字符串而不是 c++ 有效表达式的宏。

SLOT(this->exit_button_clicked()) 将不会链接到正确的广告位。您需要改写 SLOT(exit_button_clicked()) 。 Qt Creator 的自动完成功能可以为所选对象建议有效插槽。

推荐的替代方法是使用 new syntax。如果你的编译器支持 C++11,你可以在 Qt 5 中使用它。这种语法的优点是编译时检查信号、槽及其参数。

如果 menu->exit 是私有的,您不能从另一个 class 访问它,除非它被声明为 friend class。您可能需要在 MyMenu class.

中创建 public getter

即使有不使用 lambda 的解决方案,对于简单的操作,lambda 也很有效:

connect(menu->exit, &QPushButton::clicked(), [&this]{ exit_button_clicked(); });

当做某事的实际语法与您的预期如此接近时,这真是太好了:)