qt建立一个bbject类数组将按钮与lable都存入
时间: 2024-01-22 12:18:51 浏览: 28
可以通过以下代码来实现:
首先,在头文件中定义 Object 类:
```
#ifndef OBJECT_H
#define OBJECT_H
#include <QObject>
#include <QPushButton>
#include <QLabel>
class Object : public QObject
{
Q_OBJECT
public:
explicit Object(QObject *parent = nullptr);
QPushButton *button;
QLabel *label;
};
#endif // OBJECT_H
```
然后在实现文件中定义构造函数:
```
#include "object.h"
Object::Object(QObject *parent) : QObject(parent)
{
button = new QPushButton("Button");
label = new QLabel("Label");
}
```
最后,在主窗口中定义 Object 类数组,并将按钮与标签添加到布局中:
```
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "object.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
Object objects[2];
for (int i=0; i<2; i++) {
ui->horizontalLayout->addWidget(objects[i].button);
ui->horizontalLayout->addWidget(objects[i].label);
}
}
MainWindow::~MainWindow()
{
delete ui;
}
```
这样就可以将 Object 类的按钮与标签存入数组中,并添加到布局中。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![xlsm](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)