源代碼下載: learnqt-cn.cpp
Qt Qt是一個廣為人知的框架,用於開發跨平台軟件,該軟件可以在各種軟件和硬件平台上運行,代碼幾乎沒有變化,同時具有本機應用程序的能力和速度。雖然Qt最初是用C++,但也有其他語言的端口: PyQt, QtRuby, PHP-Qt, 等等.
Qt 非常適合使用圖形用户界面 (GUI) 創建應用程序。本教程是關於如何用C++去實現。
/*
* 讓我們從最經典的開始
*/
// Qt框架的所有標頭均以大寫字母'Q'開頭
#include <QApplication>
#include <QLineEdit>
int main(int argc, char *argv[]) {
// 創建一個對象來管理應用程序範圍內的資源
QApplication app(argc, argv);
// 創建行編輯widgets並在屏幕上顯示
QLineEdit lineEdit("Hello world!");
lineEdit.show();
// 啓動應用程序的事件循環
return app.exec();
}
Qt與 GUI 相關的部分與widgets及其之間的connection有關。
閲讀更多有關widgets的信息
/*
* 讓我們創建一個標籤和一個按鈕。
* 按下按鈕時應顯示一個標籤。
* Qt代碼本身就可以説明問題。
*/
#include <QApplication>
#include <QDialog>
#include <QVBoxLayout>
#include <QPushButton>
#include <QLabel>
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QDialog dialogWindow;
dialogWindow.show();
// 添加垂直佈局
QVBoxLayout layout;
dialogWindow.setLayout(&layout);
QLabel textLabel("Thanks for pressing that button");
layout.addWidget(&textLabel);
textLabel.hide();
QPushButton button("Press me");
layout.addWidget(&button);
// 按下按鈕時顯示隱藏標籤
QObject::connect(&button, &QPushButton::pressed,
&textLabel, &QLabel::show);
return app.exec();
}
注意,QObject :: connect部分。 此方法用於將一個對象的SIGNAL連接到另一個對象的SLOTS。
Signals 會被髮出當對象發生某些事情時,例如當用户按下QPushButton對象時會發出push的信號。
Slots 是可以響應於接收到的信號而執行的action。
閲讀有關SLOTS和SIGNALS的更多信息
接下來,讓我們瞭解到我們不僅可以使用標準的wigets,而且可以通過繼承擴展其行為。 讓我們創建一個按鈕並計算其被按下的次數。 為此,我們定義了自己的類 CounterLabel 。 由於特定的Qt體系結構,必須在單獨的文件中聲明它。
// counterlabel.hpp
#ifndef COUNTERLABEL
#define COUNTERLABEL
#include <QLabel>
class CounterLabel : public QLabel {
Q_OBJECT // 在每個自定義wiget中必須存在的Qt定義的宏
public:
CounterLabel() : counter(0) {
setText("Counter has not been increased yet"); // QLabel方法
}
public slots:
// 將響應按鈕按下而調用的操作
void increaseCounter() {
setText(QString("Counter value: %1").arg(QString::number(++counter)));
}
private:
int counter;
};
#endif // COUNTERLABEL
// main.cpp
// 與前面的示例幾乎相同
#include <QApplication>
#include <QDialog>
#include <QVBoxLayout>
#include <QPushButton>
#include <QString>
#include "counterlabel.hpp"
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QDialog dialogWindow;
dialogWindow.show();
QVBoxLayout layout;
dialogWindow.setLayout(&layout);
CounterLabel counterLabel;
layout.addWidget(&counterLabel);
QPushButton button("Push me once more");
layout.addWidget(&button);
QObject::connect(&button, &QPushButton::pressed,
&counterLabel, &CounterLabel::increaseCounter);
return app.exec();
}
當然,Qt框架比本教程介紹的部分要複雜得多,因此請仔細閲讀和練習。
進一步閲讀
- Qt 4.8 tutorials
- Qt 5 tutorials
祝你好運,生活愉快!
有建議?或者發現什麼錯誤?在Github上開一個issue,或者發起pull request!
原著Aleksey Kholovchuk,並由0個好心人修改。
© 2022 Aleksey Kholovchuk
Translated by: GengchenXU
本作品採用 CC BY-SA 3.0 協議進行許可。