gpt4 book ai didi

c++ - 动态更改文本 qlabel

转载 作者:行者123 更新时间:2023-11-30 03:35:05 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com