gpt4 book ai didi

c++ - 使用派生类时出现 Qt 运行时错误

转载 作者:行者123 更新时间:2023-11-27 23:18:03 25 4
gpt4 key购买 nike

我只是想在 Qt 中制作一个程序,您可以在其中按下两个按钮之一,QLabel 的文本会根据您更改的按钮而变化。运行脚本时出现运行时错误。我为这个程序做了一个“自定义”窗口类:

这是头文件:

#ifndef MW_H
#define MW_H
#include <QString>
#include <QPushButton>
#include <QLabel>
#include <QGridLayout>
#include <QDialog>

class MW: public QDialog
{
Q_OBJECT
private:
QPushButton* one;
QPushButton* two;
QLabel* three;
QGridLayout* mainL;
public:
MW();
private slots:
void click_1();
void click_2();

};

#endif // MW_H

这是 header 的 .cpp:

#include "MW.h"

MW :: MW()
{

//create needed variables
QGridLayout* mainL = new QGridLayout;
QPushButton* one = new QPushButton("Set1");
QPushButton* two = new QPushButton("Set2");
QLabel* three = new QLabel("This text will be changed");

//connect signals and slots

connect(one, SIGNAL(clicked()), this, SLOT(click_1()));
connect(two, SIGNAL(clicked()), this, SLOT(click_2()));

// create layout
mainL->addWidget(one, 1, 0);
mainL->addWidget(two, 1, 1);
mainL->addWidget(three, 0, 1);
setLayout(mainL);
}


void MW :: click_1()
{
three->setText("One Clicked me!");
}

void MW :: click_2()
{
three->setText("Two Clicked me!");
}

最后是主要功能:

#include <QApplication>
#include "MW.h"

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MW w;
w.setAttribute(Qt::WA_QuitOnClose);
w.show();

return a.exec();
}

这是我正在做的第三个左右的小型学习计划,我遇到了同样的问题。它开始变得有点烦人了。任何帮助将不胜感激。

最佳答案

错误在于您的构造函数中。

QLabel* three = new QLabel("This text will be changed");

这一行将新的 QLabel 存储到局部变量而不是类变量。因此,您的类变量 three 保持为空。 (与其他三个变量一样,但这不是这里的问题,因为您不会在构造函数之外访问它们)

为了让长话短说,修改你的代码如下:

MW :: MW()
{

//create needed variables
mainL = new QGridLayout;
one = new QPushButton("Set1");
two = new QPushButton("Set2");
three = new QLabel("This text will be changed"); //This line, actually.

//connect signals and slots

connect(one, SIGNAL(clicked()), this, SLOT(click_1()));
connect(two, SIGNAL(clicked()), this, SLOT(click_2()));

// create layout
mainL->addWidget(one, 1, 0);
mainL->addWidget(two, 1, 1);
mainL->addWidget(three, 0, 1);
setLayout(mainL);
}

像这样,类中的变量将被填充,您的代码应该按预期工作。

关于c++ - 使用派生类时出现 Qt 运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15174636/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com