Qt文件閱讀筆記-Widgets Tutorial官方解析及例項
阿新 • • 發佈:2018-12-13
目錄
官方解析
QWiget通常作為其他視窗的容器,可以使用QWidget到達最小代價定義自定義控制元件(經驗:通常可以採用子類QLabel做成自定義控制元件) 可以通過構建他的父類物件來指定他的物件樹。
注意:當刪除視窗後內部的控制元件都會自動刪除!
#include <QtWidgets> // Include header files for application components. // ... int main(int argc, char *argv[]) { QApplication app(argc, argv); // Set up and show widgets. // ... return app.exec(); }
argc與*argv[]通過命令列可以對app進行配置; QApplication::exec()進入Qt的事件迴圈;
博主栗子
來驗證一下關閉主視窗後是否釋放了子控制元件,ui檔案如下:
原始碼如下:
mylabel.h
#ifndef MYLABEL_H #define MYLABEL_H #include <QLabel> class MyLabel : public QLabel { Q_OBJECT public: MyLabel(QWidget *parent = 0); ~MyLabel(); signals: public slots: }; #endif // MYLABEL_H
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
main.cpp
#include "widget.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); Widget w; w.show(); return a.exec(); }
mylabel.cpp
#include "mylabel.h"
#include <QDebug>
MyLabel::MyLabel(QWidget *parent) : QLabel(parent)
{
}
MyLabel::~MyLabel()
{
qDebug()<<"MyLabel::~MyLabel() called!";
}
widget.cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
}
Widget::~Widget()
{
delete ui;
}
程式執行截圖如下: