c++ - 未显示继承类

标签 c++ qt

我有两个类:第一个是 QWidget 的继承者,第二个是第一个类的继承者。当我启动我的程序时,我得到 2 个一流的窗口。为什么?还有一个问题。 Second::Second(QWidget *pwgt): First(pwgt) - 这个字符串正确吗?即我应该将 pwgt 发送给第一类的构造函数吗?

第一类.h

#ifndef FIRSTCLASS_H
#define FIRSTCLASS_H
#include <QtGui>

class First: public QWidget
{
    Q_OBJECT

protected:
    QLabel *firstText;
    QPushButton *firstButton;

public:
    First(QWidget *pwgt = 0);
};

#endif // FIRSTCLASS_H

第一类.cpp

#include "firstclass.h"

First::First(QWidget *pwgt)
{
    firstText = new QLabel("First Class Text");
    firstButton = new QPushButton("First Class Button");

    QVBoxLayout *lay = new QVBoxLayout;
    lay->addWidget(firstText);
    lay->addWidget(firstButton);

    this->setLayout(lay);
}

第二类.h

#ifndef SECONDCLASS_H
#define SECONDCLASS_H
#include <QtGui>
#include "firstclass.h"

class Second: public First
{
    Q_OBJECT

private:
    QLabel *secondText;
    QPushButton *secondButton;

public:
    Second(QWidget *pwgt = 0);

public slots:
    void changeText();
};

#endif // SECONDCLASS_H

第二类.cpp

#include "secondclass.h"

Second::Second(QWidget *pwgt): First(pwgt)
{
    secondText = new QLabel("Second Class Text");
    secondButton = new QPushButton("Second Class Button");

    QVBoxLayout *lay = new QVBoxLayout;
    lay->addWidget(secondText);
    lay->addWidget(secondButton);

    connect(secondButton, SIGNAL(clicked()), this, SLOT(changeText()));

    this->setLayout(lay);
}

void Second::changeText()
{
    firstText->setText("From second class");
}

主要.cpp

#include "firstclass.h"
#include "secondclass.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    First first;
    Second second;

    first.show();
    second.show();

    return a.exec();
}

最佳答案

问题是您在 First 类的构造函数中使用 setLayout(lay); 设置了布局。这是正确的,尤其是当您创建 First 类的对象时。但是,当您创建 Second 类的对象时,First 类的构造函数仍然会被调用。在以下代码中:

First first;   // Calls the First class constructor
Second second; // Calls both First and Second class constructors

正如 Qt 文档所述

If there already is a layout manager installed on this widget, QWidget won't let you install another.

这意味着一旦您在 First 类构造函数中设置布局,将忽略在 Second 类中再次设置它的尝试。因此,您在两种情况下都会看到第一个布局。

WRT 你的第二个问题:是的,通常你必须将参数传递给基类构造函数。您甚至必须将父级传递给 First 类构造函数中的 QWidget 类:

First::First(QWidget *pwgt) : QWidget(pwgt) {}

关于c++ - 未显示继承类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25898664/

相关文章:

c++ - 指向 C++ 中的结构的指针 - 从控制台读取?

c++ - 如何用 C++ 编写随机大写字符生成器?

c++ - QList::iterator 只返回 (error)0

qt - WebEngineView QML 类型需要安装flash player

c++ - 无法在 Release 模式下在 Qt 中加载 QSQLCIPHER

c++ - 如何从外部分离 gdb session ?

c++ - 编译器无法识别 Getline

linux - QT umount() 函数不起作用

c++ - 我可以使用 Qt 检测 QWERTY/AZERTY 键盘吗?

python - 同时运行 c++ 和 python 脚本会导致问题