未显示继承的类

时间:2014-09-17 19:21:20

标签: c++ qt

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

firstclass.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

firstclass.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);
}

secondclass.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

secondclass.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");
}

的main.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();
}

2 个答案:

答案 0 :(得分:1)

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

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

正如Qt文档所述

  

如果此小部件上已安装了布局管理器,QWidget将不允许您安装另一个布局管理器。

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

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

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

答案 1 :(得分:1)

在第二个小部件上调用setLayout两次 - 一次在First构造函数中,然后再在第二个构造函数中调用。但第二个将被忽略:http://qt-project.org/doc/qt-4.8/qwidget.html#setLayout

如果他们看起来完全不同,你为什么还要这样继承。