这段代码中的connect
函数中,第三个参数是错误的。在这里,你将信号与窗口对象(&window
)连接,但是窗口对象并没有定义一个名为handleButtonClick1
的槽函数。
正确的做法是将信号与主窗口对象(MainWindow
)中的槽函数进行连接。如果你想要连接到主窗口的槽函数,请使用类名作为接收者对象。
下面是修正后的代码:
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MainWindow window; // 创建主窗口对象
QVBoxLayout* layout = new QVBoxLayout(&window); // 创建垂直布局
QLabel* label = new QLabel("你今天开心吗?", &window); // 创建标签,显示文本
QPushButton* button1 = new QPushButton("是的", &window); // 创建按钮
QPushButton* button2 = new QPushButton("不开心", &window);
connect(button1, &QPushButton::clicked, &window, &MainWindow::handleButtonClick1);
layout->addWidget(label); // 将标签添加到布局中
layout->addWidget(button1); // 将按钮添加到布局中
layout->addWidget(button2); // 将按钮添加到布局中
window.setLayout(layout); // 设置窗口的主要布局为上述垂直布局
window.show();
return app.exec();
}
请确保在MainWindow
类中定义了名为handleButtonClick1
的槽函数,并将其声明为public slots
。
内容由零声教学AI助手提供,问题来源于学员提问