简体   繁体   中英

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?

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 .

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.

I know how to create static variables, but when comes to declare a staic QLabel , I found it difficult to achieve it.

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 . 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? 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:

public:
    static QLabel * label;

in implementation file, on top:

QLabel *Form::label = 0;

in Form constructor:

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

Again, this makes sense if you have one Form instance only. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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