當創建用C GUI ++和Qt你可以這樣創建例如標籤:C++ - 爲什麼我要在堆上創建這些小部件?
QLabel* label = new QLabel("Hey you!", centralWidgetParent);
這在堆上創建對象,將呆在那裏,直到我手動刪除或父被摧毀。我現在的問題是爲什麼我需要一個指針?爲什麼不在堆棧上創建它?
//Create a member variable of Class MainWindow
QLabel label;
//Set parent to show it and give a text so the user can see it
QWidget* centralWidget = new QWidget(this); //Needed to add widgets to the window
this->setCentralWidget(centralWidget);
label.setParent(centralWidget);
label.setText("Haha");
這工作正常,我可以看到標籤,它並沒有消失。
我們在C++中使用指針讓事物壽命更長,因此我們可以在各種範圍內使用對象。但是,當我創建一個成員變量,它不會留下,直到對象被破壞?
編輯: 也許我沒有說清楚。這是MainWindow類:
class MainWindow : public QMainWindow
{
Q_OBJECT
QLabel label; //First introduced here...
public:
MainWindow(QWidget *parent = 0);
~MainWindow();
};
//Constructor
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
QWidget* centralWidget = new QWidget(this);
this->setCentralWidget(centralWidget);
label.setParent(centralWidget);
label.setText("Haha");
}
嗯......這至少讓人感覺。謝謝。 – Davlog