gpt4 book ai didi

c++ - qt中什么时候应该将子对象声明为其父类的成员变量?

转载 作者:行者123 更新时间:2023-11-28 05:13:07 27 4
gpt4 key购买 nike

//disconnect.h
#include <QWidget>
#include <QPushButton>

class Disconnect : public QWidget {

Q_OBJECT

public:
Disconnect(QWidget *parent = 0);

private slots:
void onClick();
void onCheck(int);

private:
QPushButton *clickBtn;
};

//disconnect.cpp
#include <QTextStream>
#include <QCheckBox>
#include <QHBoxLayout>
#include "disconnect.h"

Disconnect::Disconnect(QWidget *parent)
: QWidget(parent) {

QHBoxLayout *hbox = new QHBoxLayout(this);
hbox->setSpacing(5);

clickBtn = new QPushButton("Click", this);
hbox->addWidget(clickBtn, 0, Qt::AlignLeft | Qt::AlignTop);

QCheckBox *cb = new QCheckBox("Connect", this);
cb->setCheckState(Qt::Checked);
hbox->addWidget(cb, 0, Qt::AlignLeft | Qt::AlignTop);

connect(clickBtn, &QPushButton::clicked, this, &Disconnect::onClick);
connect(cb, &QCheckBox::stateChanged, this, &Disconnect::onCheck);
}

void Disconnect::onClick() {

QTextStream out(stdout);
out << "Button clicked" << endl;
}

void Disconnect::onCheck(int state) {

if (state == Qt::Checked) {
connect(clickBtn, &QPushButton::clicked, this, &Disconnect::onClick);
} else {
disconnect(clickBtn, &QPushButton::clicked, this,
&Disconnect::onClick);
}
}

//main.cpp
#include <QApplication>
#include "disconnect.h"

int main(int argc, char *argv[]) {

QApplication app(argc, argv);

Disconnect window;

window.resize(250, 150);
window.setWindowTitle("Disconnect");
window.show();

return app.exec();
}

在上面的代码中,一个Disconnect对象有两个子对象——一个QPushButton和一个QcheckBox,但是类Disconnect只有一个QPushButton指针,没有一个QcheckBox指针。谁能告诉我在qt中什么时候应该将子对象声明为其父类的成员变量?

最佳答案

Can anyone tell me when should the child object be declared as a member variable of its parent class in qt?

如果您认为您需要从父类的其他方法调用(或以其他方式访问)子对象的方法(如您的示例代码使用 clickBtn,从 引用它onCheck 方法),那么您需要创建一个成员变量,它是指向该子对象的指针,以允许您这样做。

另一方面,如果您不需要在创建子对象的方法之外访问子对象,那么您可以通过声明指向子对象的指针来使父类的定义更短、更简单。对象仅在创建方法中作为局部变量。

关于c++ - qt中什么时候应该将子对象声明为其父类的成员变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43164324/

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