I have the following Qt class:
mainwindow.h
class MainWindow : public QWidget {
Q_OBJECT
QPushButton* m_button;
public:
explicit MainWindow();
};
mainwindow.cpp
MainWindow::MainWindow() {
auto main_layout = new QHBoxLayout;
m_button = new QPushButton("Press me");
main_layout->addWidget(m_button);
setLayout(main_layout);
connect(m_button, &QPushButton::pressed, [this] {
m_button->setText("Presse me again");
});
}
It features a button which once pressed will change its text to "Press me again". I use a lambda function and I am capturing by copy this
to access the button inside the lambda.
As the QPushButton is allocated on the heap, I think that making it a class member is an unnecessary step. My question: Are there any drawbacks if I instead use it as a local pointer which I would capture by copy in the connect
lambda ? It would look like this:
mainwindow.h
class MainWindow : public QWidget {
Q_OBJECT
public:
explicit MainWindow();
};
mainwindow.cpp
MainWindow::MainWindow() {
auto main_layout = new QHBoxLayout;
auto button = new QPushButton("Press me");
main_layout->addWidget(button);
setLayout(main_layout);
connect(button, &QPushButton::pressed, [button] { // I am copying the button's address here
button->setText("Presse me again");
});
}
One thing to note: Qt manages the destruction of all Qt classes automatically, so no need to call the button's destructor later if I understood correctly this conversation.