QT开发中文网

#include "mainwindow.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); QWidget window; QVBoxLayout* layout = new QVBoxLayout(&window); // 创建垂直布局 QLabel* label = new QLabel("你今天开心吗?", &window); // 创建标签,显示文本 ...

这段代码中的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助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://qt.0voice.com/?id=9129

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?