上節講了項目文件組成,這節進行詳細說明。
1).pro文件
2) main主函數文件
3) 窗體相關文件
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
//namespace聲明一個UI空間,包含一個MainWindow類
namespace Ui {
class MainWindow;
}
//MainWindow類定義,繼承QMainWindow類的定義
class MainWindow : public QMainWindow
{
//使用宏Q_OBJECT,是一個使用信號與槽必須的一個宏
Q_OBJECT
//定義MainWindow類的構造函數與析構函數
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
//定義一個指針
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
Mainwindow.c
#include "mainwindow.h"
#include "ui_mainwindow.h"
//這個函數中只有構造函數與析構函數
//構造函數:執行父類QMainWindow的構造函數,
//創建一個Ui::MainWindow類的對象的ui。
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
//這個函數執行窗口的生成與各種屬性的設置,以及信號與槽的關聯
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
//刪除用new創建的指針ui
delete ui;
}
Mainwindow.ui
不需要知道這個文件是怎麼生成的,只需要在UI設計界面進行可視化設計即可。
ui_mainwindow.h
//定義Ui_MainWindow,用於封裝界面
class Ui_MainWindow
{
public:
//每在界面上拖入一個組件,這裏機會生成一個指針變量
QWidget *centralWidget;
QLabel *label;
QMenuBar *menuBar;
QToolBar *mainToolBar;
QStatusBar *statusBar;
//用於創建各個界面的組件,並設置其位置、大小、字體等相關屬性。
void setupUi(QMainWindow *MainWindow)
{
if (MainWindow->objectName().isEmpty())
MainWindow->setObjectName(QStringLiteral("MainWindow"));
MainWindow->resize(400, 300);
centralWidget = new QWidget(MainWindow);
centralWidget->setObjectName(QStringLiteral("centralWidget"));
label = new QLabel(centralWidget);
label->setObjectName(QStringLiteral("label"));
label->setGeometry(QRect(90, 70, 211, 71));
QFont font;
font.setFamily(QStringLiteral("Adobe Myungjo Std M"));
font.setPointSize(20);
label->setFont(font);
MainWindow->setCentralWidget(centralWidget);
menuBar = new QMenuBar(MainWindow);
menuBar->setObjectName(QStringLiteral("menuBar"));
menuBar->setGeometry(QRect(0, 0, 400, 23));
MainWindow->setMenuBar(menuBar);
mainToolBar = new QToolBar(MainWindow);
mainToolBar->setObjectName(QStringLiteral("mainToolBar"));
MainWindow->addToolBar(Qt::TopToolBarArea, mainToolBar);
statusBar = new QStatusBar(MainWindow);
statusBar->setObjectName(QStringLiteral("statusBar"));
MainWindow->setStatusBar(statusBar);
retranslateUi(MainWindow);
QMetaObject::connectSlotsByName(MainWindow);
} // setupUi
void retranslateUi(QMainWindow *MainWindow)
{
MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", Q_NULLPTR));
label->setText(QApplication::translate("MainWindow", "\344\275\240\345\245\275\357\274\214\344\270\226\347\225\214\357\274\201\357\274\201", Q_NULLPTR));
} // retranslateUi
};
//定義namespace Ui ,並定義一個從Ui_MainWindow繼承的類MainWindow
namespace Ui {
class MainWindow: public Ui_MainWindow {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_MAINWINDOW_H