Dynamically change text qlabel

血红的双手。 提交于 2021-02-17 03:16:43

问题


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");

But ultimately label = "One"

Ok i understood. I just suffered in class constructor.

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

But question is actually:

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?


回答1:


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

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).

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



来源:https://stackoverflow.com/questions/41533266/dynamically-change-text-qlabel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!