1

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?

Tipok
  • 675
  • 8
  • 26
  • Do you need to replace those objects? Probably not. – LogicStuff Jan 08 '17 at 13:38
  • 2
    You should only create a new label once, and pass a pointer to the parent `QWidget` to it's constructor. This way, it is cleaned up automatically when the parent is destroyed. Then, in the `setTextToHint` function you can update the existing's label text with `m_label->setText(QString::fromUtf8(str.c_str()))`. – Unimportant Jan 08 '17 at 14:20
  • 2
    I think your question has devolved into a duplicate of http://stackoverflow.com/questions/3264420/lifetime-of-qt-objects – tinkertime Jan 08 '17 at 14:50

1 Answers1

2

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

Community
  • 1
  • 1
tinkertime
  • 2,972
  • 4
  • 30
  • 45