简体   繁体   English

如何在Qt中创建静态QLabel

[英]how to create static QLabel in Qt

Is it possible to create some static QLabel s in one class, and other classes can access its QLabel s variable and apply changes to the QLabel s without creating its object? 是否可以在一个类中创建一些static QLabel ,而其他类可以访问其QLabel的变量并将更改应用于QLabel而无需创建其对象?

I found some answers online like if you want to access one class variables without creating its object in another class, you have to make its data static . 我在网上找到了一些答案,例如,如果要访问一个类变量而不在另一个类中创建其对象,则必须使其数据static

So basically what I am trying to do here is accessing and changing one class variables, for me it is QLabel s, in another class without creating its object. 因此,基本上,我在这里要做的是访问和更改一个类变量,对我来说,它是QLabel ,而在另一个类中却不创建其对象。

I know how to create static variables, but when comes to declare a staic QLabel , I found it difficult to achieve it. 我知道如何创建static变量,但是当声明一个staic QLabel ,我发现很难实现它。

I think you may just make the label accessible , ie expose it as a public member. 我认为您可以使标签可访问 ,即将其作为公共成员公开。 Say you have a Form class, and a label QLabel in its ui . 假设您有一个Form类,并且在ui有一个label QLabel Add this method to the class: 将此方法添加到类中:

public:
    QLabel * label();

the implementation is just: 实现只是:

QLabel *Form::label()
{
    return ui->label;
}

If all you need to expose is the label text property, just add these two accessors methods: 如果您需要公开的只是标签文本属性,只需添加以下两个访问器方法:

public:
    QString labelText();
    void setLabelText(QString & text);

in implementation file: 在实现文件中:

QString Form::labelText()
{
    return ui->label->text();
}

void Form::setLabelText(QString &text)
{
    ui->label->setText(text);
}

These last strategy fits encapsulation better. 这些最后的策略更适合封装。

About having it static: what if you have more than one instance of the Form class? 关于使其静态:如果您有多个Form类的实例怎么办? Which label is supposed to be pointed to by the static member? 静态成员应该指向哪个标签? If you are 100% sure you will have only one instance of the widget, you can add a static public QLabel * member: 如果您100%确定只有小部件的一个实例,则可以添加一个静态的公共QLabel *成员:

public:
    static QLabel * label;

in implementation file, on top: 在实现文件中,位于顶部:

QLabel *Form::label = 0;

in Form constructor: Form构造函数中:

ui->setupUi(this);
if(label == 0)
{
    label = ui->label;
}

Again, this makes sense if you have one Form instance only. 同样,如果仅具有一个Form实例,则这很有意义。 Otherwise, the static pointer will point forever to the label of the widget which was created first (and, dangerously, to nothing when that instance gets destroyed). 否则,静态指针将永远指向最先创建的窗口小部件的标签(危险的是,当该实例被销毁时,它什么也没有)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM