问题
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