gpt4 book ai didi

c++ - 未显示继承类

转载 作者:行者123 更新时间:2023-11-30 04:01:12 25 4
gpt4 key购买 nike

我有两个类:第一个是 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/

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