把数据传入Widget类中
时间: 2024-02-15 07:06:03 浏览: 19
在Qt中,可以通过构造函数、成员函数等方式将数据传入Widget类中。下面以一个简单的例子为例,介绍一些常用的方法。
假设有一个Widget类,需要显示一个字符串,可以在构造函数中将字符串传入。例如:
```
class MyWidget : public QWidget {
public:
MyWidget(const QString& str, QWidget* parent = nullptr) : QWidget(parent) {
QLabel* label = new QLabel(str, this);
label->setAlignment(Qt::AlignCenter);
setFixedSize(200, 100);
}
};
```
这里在构造函数中接收一个字符串参数`str`,并使用`QLabel`显示这个字符串。最后设置了Widget的大小为200x100。
如果需要在Widget类的其他成员函数中使用这个字符串,可以将字符串作为成员变量存储。例如:
```
class MyWidget : public QWidget {
public:
MyWidget(const QString& str, QWidget* parent = nullptr) : QWidget(parent), m_str(str) {
QLabel* label = new QLabel(str, this);
label->setAlignment(Qt::AlignCenter);
setFixedSize(200, 100);
}
void printStr() {
qDebug() << m_str;
}
private:
QString m_str;
};
```
这里在构造函数中将字符串`str`存储在成员变量`m_str`中,并在`printStr()`函数中输出这个字符串。这样,就可以在Widget类的其他函数中使用这个字符串了。
如果需要动态地更新Widget中的数据,可以添加一个公共的成员函数,用于更新显示的数据。例如:
```
class MyWidget : public QWidget {
public:
MyWidget(QWidget* parent = nullptr) : QWidget(parent) {
m_label = new QLabel(this);
m_label->setAlignment(Qt::AlignCenter);
setFixedSize(200, 100);
}
void updateStr(const QString& str) {
m_label->setText(str);
}
private:
QLabel* m_label;
};
```
这里添加了一个公共的成员函数`updateStr()`,用于更新显示的字符串。在函数中,使用`setText()`函数更新`QLabel`的显示内容。这样,就可以通过调用`updateStr()`函数动态地更新Widget中的数据了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)