[英]Dynamically change text qlabel
Sorry for my english. 对不起我的英语不好。 I need to change the text qlabel dynamically.
我需要动态更改文本qlabel。
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"
但最终
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. 仍然我想问问,使用ql对象的stl智能指针不好。 I can not use smart pointers from the library QT only STL.
我不能使用仅来自QT库STL的智能指针。 What do i do?
我该怎么办?
You should have setTextToHint
only call setText()
, everything else should be done on construction of the Game
. 您应该只让
setTextToHint
调用setText()
,其他所有事情都应该在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. 根据您对使用stl智能指针的评论,我认为您担心直接使用
new
导致内存泄漏。 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). 实际上,您的用法基本上是正确的-Qt在使用正确的父子设置时提供了它自己的内存管理,因此没有理由将Qt对象分配与stl智能指针混合使用(通常)。
Much more conversation on this topic can be found here: stackoverflow.com/questions/3264420/lifetime-of-qt-objects 有关此主题的更多讨论可以在这里找到: stackoverflow.com/questions/3264420/lifetime-of-qt-objects
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.