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

标签 c++ qt

我只是想在 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/

相关文章:

c++ - 错误: taking address of temporary [-fpermissive]

c++ - 我的程序无法写入 Windows 驱动器

c++ - 为什么 select(QTextCursor::BlockUnderCursor) 包含一个额外的垃圾字符?

python - 使用QWebElement解析HTML,如何提取图像?

python - PyQt5 - 调整标签大小以填充整个窗口

qt - 如何从QChartView或QChart中删除边距

c++ - 使用c++、linux绘制 vector 图

C++:为什么 decltype (*this) 返回一个引用?

c++ - Qt/C++11 抛出,方法原型(prototype)中的最终覆盖

c++ - 如何启用clang的模块TS?