c++ - 动态更改文本 qlabel

标签 c++ qt c++11 stl

对不起我的英语。我需要动态更改文本 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);
}

我使用这个函数两次:

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

但最终label = "One"

好的,我明白了。我只是在类构造函数中受苦。

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

但问题其实是:

还是想问问用STL智能指针这个qt对象不好吗。我不能使用 QT 库中的智能指针,只有 STL。我该怎么办?

最佳答案

您应该让 setTextToHint 只调用 setText(),其他所有事情都应该在构建 Game 时完成。

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

有关此主题的更多对话可在此处找到: stackoverflow.com/questions/3264420/lifetime-of-qt-objects

关于c++ - 动态更改文本 qlabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41533266/

相关文章:

c++ - 我可以在 c++11 中的 std::deque 上使用 std::max_element() 吗?

c++ - 自动生成成员函数的 const 重载

c++ - 如何将 "using"用于函数?

c++ - 这条代码中这条毯子是什么意思?

c++ - 为什么在 C++ 中说 "can' t find constructor?

c++ - 在 Qt 中制作关于 GUI 窗口的游戏

c# - 是否可以像在 VS C++ 中一样从 C# DLL 导出函数?

c++ - 在 Release 模式下崩溃,在 Debug 模式下遇到错误

windows - Qt Creator 调试

c++ - 命名空间被视为类型