
以下列出 Qt 中常用的視窗元件
| 元件名稱 | 類別名稱 |
|---|---|
| 視窗 | QWidget |
| 標籤 | QLabel |
| 按鈕 | QPushButton |
| 核取方塊 | QCheckBox |
| 選取方塊 | QRadioButton |
| 下拉式列表 | QComboBox |
| 列表 | QListWidget |
| 捲動軸 | QScrollBar |
| 文字方塊 | QLineEdit |
| 文字區域 | QTextEdit |
| 下拉式選單列 | QMenuBar |
| 下拉式選單 | QMenu |
| 工具列 | QToolBar |
| 檔案視窗 | QFileDialog |
| 色彩視窗 | QColorDialog |
| 字型視窗 | QFontDialog |
| 對話視窗 | QMessageBox |
我們使用 Qt 設計 GUI ,假設專案名稱為 Demo2 ,程式將會分成三個部份
- Demo2.h
- Demo2.cpp
- main.cpp
Demo2.h 為宣告 Demo2 類別的地方
#ifndef DEMO2_H
#define DEMO2_H
#include <QWidget>
class QLabel;
class QPushButton;
class QCheckBox;
class QRadioButton;
class QLineEdit;
// Demo2 繼承自 QWidget
class Demo2 : public QWidget {
Q_OBJECT
public:
Demo2(QWidget *parent = 0);
private:
QLabel *b1;
QPushButton *b2;
QCheckBox *b3;
QRadioButton *b4;
QLineEdit *b5;
};
#endif
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:Demo2.h
功能:示範 C++ 程式
作者:張凱慶
時間:西元 2012 年 10 月 */基本的 GUI 就是設計繼承 (inherit) 自 QWidget 的類別 (class) ,然後建立版面編排物件 (object) ,並將視窗元件加入版面編排物件
#include <QtGui>
#include "Demo2.h"
Demo2::Demo2(QWidget *parent) : QWidget(parent) {
// 將成員變數屬性初始化
b1 = new QLabel(tr("QLabel"));
b2 = new QPushButton(tr("QPushButton"));
b3 = new QCheckBox(tr("QCheckBox"));
b4 = new QRadioButton(tr("QRadioButton"));
b5 = new QLineEdit;
// 建立版面樣式物件
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(b1);
layout->addWidget(b2);
layout->addWidget(b3);
layout->addWidget(b4);
layout->addWidget(b5);
// 設定版面樣式與視窗標題
setLayout(layout);
setWindowTitle(tr("Demo2"));
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:Demo2.cpp
功能:示範 C++ 程式
作者:張凱慶
時間:西元 2012 年 10 月 */所謂繼承是使子類別 (subclass) 具有父類別 (superclass) 的特性,此例中 Demo2 為子類別,繼承父類別 QWidget ,中間用冒號 : 隔開。因此 Demo2 就是一種 QWidget , Demo2 就具有 QWidget 所定義的成員 (member) 。
最後在 main.cpp 中建立 Demo2 後,呼叫成員函數 (member function) show() ,執行程式就會顯示 GUI
#include <QtGui>
#include "Demo2.h"
int main(int argv, char **args)
{
QApplication app(argv, args);
Demo2 demo;
demo.show();
return app.exec();
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:main.cpp
功能:示範 C++ 程式
作者:張凱慶
時間:西元 2012 年 10 月 */這裡我們需要注意一下
// 建立版面樣式物件 QVBoxLayout *layout = new QVBoxLayout; layout->addWidget(b1); layout->addWidget(b2); layout->addWidget(b3); layout->addWidget(b4); layout->addWidget(b5);
-> 這個是箭頭運算子,由於 layout 是指標 (pointer) ,用指標呼叫函數成員便得用箭頭運算子。
編譯執行這個專案,結果如下

Demo2 類別是採用 QVBoxLayout 的排版樣式, QVBoxLayout 是從上而下的一格一格版面,因此加入視窗元件時 QLabel 在最上方, QPushButton 其次,餘下類推。 Qt 還有很多排版管理,我們來看一下吧!
| 中英文術語對照 | |
|---|---|
| 標籤 | label |
| 按鈕 | button |
| 選單 | menu |
| 文字方塊 | textfield |
| 繼承 | inherit |
| 類別 | class |
| 物件 | object |
| 子類別 | subclass |
| 父類別 | superclass |
| 成員 | member |
| 成員函數 | member function |
| 指標 | pointer |
您可以繼續參考
GUI 篇
相關目錄
回 C++ 入門指南
回 C++ 教材目錄
回首頁
參考資料
Qt Developer Network
沒有留言:
張貼留言