动态更改文本qlabel [英] Dynamically change text qlabel

查看:71
本文介绍了动态更改文本qlabel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,我的英语.我需要动态更改文本qlabel.

Sorry for my english. I need to change the text qlabel dynamically.

class Game:
{
...
    std::shared_ptr<QWidget> m_hint;
    QLabel *m_label;
    QHBoxLayout *m_layout;
}

void Game::setTextToHint(std::string str)
{
    m_label = new QLabel();
    m_layout = new QHBoxLayout();
    m_label->setText(QString::fromUtf8(str.c_str()));
    m_layout->addWidget(m_label);
    m_hint->setLayout(m_layout);
}

例如,我两次使用此功能:

And i use this function eg twice:

setTextToHint("One");
setTextToHint("First");

但最终 label ="One"

好的,我明白了.我只是在类构造器中受苦.

Ok i understood. I just suffered in class constructor.

m_label = new QLabel();
m_layout = new QHBoxLayout();

但问题实际上是:

我还是想问问使用stl智能指针这个qt对象不好.我不能使用仅来自QT库STL的智能指针.我该怎么办?

Still I would like to ask to use stl smart pointers this qt object not good. I can not use smart pointers from the library QT only STL. What do i do?

推荐答案

您应该只将 setTextToHint 调用 setText(),其他所有操作都应在构建游戏.

You should have setTextToHint only call setText(), everything else should be done on construction of the Game.

根据您有关使用stl智能指针的评论,我认为您担心直接使用 new 会导致内存泄漏.实际上,您的用法基本上是正确的-Qt在使用正确的父子设置时提供了它自己的内存管理,因此(通常)没有理由将Qt对象分配与stl智能指针混合使用.

As per your comment regarding use of stl smart pointers, I presume you're worried about memory leaks per your usage of new directly. In fact your usage is mostly correct - Qt offers it's own memory management while using a proper parent-child setup, so no reason to mix Qt object allocations with stl smart pointers (in general).

有关此主题的更多讨论可以在这里找到: stackoverflow.com/questions/3264420/lifetime-of-qt-objects

Much more conversation on this topic can be found here: stackoverflow.com/questions/3264420/lifetime-of-qt-objects

这篇关于动态更改文本qlabel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆