跳到主要内容

Qt 知识速查表

常用类速查

核心类

类名功能头文件
QApplication应用程序入口<QApplication>
QObject所有 Qt 对象的基类<QObject>
QWidget所有 UI 控件的基类<QWidget>
QMainWindow主窗口<QMainWindow>
QDialog对话框基类<QDialog>

基础控件

类名功能头文件
QLabel标签<QLabel>
QPushButton按钮<QPushButton>
QLineEdit单行输入<QLineEdit>
QTextEdit多行文本<QTextEdit>
QComboBox下拉框<QComboBox>
QCheckBox复选框<QCheckBox>
QRadioButton单选按钮<QRadioButton>
QSlider滑块<QSlider>
QProgressBar进度条<QProgressBar>

高级控件

类名功能头文件
QListWidget列表<QListWidget>
QTableWidget表格<QTableWidget>
QTreeWidget树形<QTreeWidget>
QTabWidget标签页<QTabWidget>
QStackedWidget堆叠窗口<QStackedWidget>
QSplitter分割器<QSplitter>

布局类

类名功能头文件
QVBoxLayout垂直布局<QVBoxLayout>
QHBoxLayout水平布局<QHBoxLayout>
QGridLayout网格布局<QGridLayout>
QFormLayout表单布局<QFormLayout>

对话框

类名功能头文件
QMessageBox消息框<QMessageBox>
QFileDialog文件对话框<QFileDialog>
QInputDialog输入对话框<QInputDialog>
QColorDialog颜色对话框<QColorDialog>
QFontDialog字体对话框<QFontDialog>

网络类

类名功能头文件
QNetworkAccessManagerHTTP 管理<QNetworkAccessManager>
QTcpSocketTCP 客户端<QTcpSocket>
QTcpServerTCP 服务器<QTcpServer>
QUdpSocketUDP 通信<QUdpSocket>

信号槽连接方式

// 1. 传统语法(Qt 4)
connect(sender, SIGNAL(signal()), receiver, SLOT(slot()));

// 2. 新语法(Qt 5+,推荐)
connect(sender, &Sender::signal, receiver, &Receiver::slot);

// 3. Lambda 表达式
connect(sender, &Sender::signal, [=]() {
// 处理代码
});

// 4. 带连接类型
connect(sender, &Sender::signal, receiver, &Receiver::slot, Qt::QueuedConnection);

常用宏

用途
Q_OBJECT启用元对象系统(必须)
SIGNAL()标记信号(传统语法)
SLOT()标记槽(传统语法)
Q_PROPERTY()声明属性
Q_INVOKABLE允许从元对象系统调用
Q_SLOTS声明槽函数区域
Q_SIGNALS声明信号区域

常用枚举值

对齐方式

Qt::AlignLeft      // 左对齐
Qt::AlignRight // 右对齐
Qt::AlignCenter // 居中
Qt::AlignTop // 顶部对齐
Qt::AlignBottom // 底部对齐
Qt::AlignHCenter // 水平居中
Qt::AlignVCenter // 垂直居中

连接类型

Qt::AutoConnection          // 自动选择(默认)
Qt::DirectConnection // 直接调用
Qt::QueuedConnection // 队列连接(异步)
Qt::BlockingQueuedConnection // 阻塞队列连接
Qt::UniqueConnection // 唯一连接

窗口标志

Qt::Window                  // 普通窗口
Qt::Dialog // 对话框
Qt::Popup // 弹出窗口
Qt::Tool // 工具窗口
Qt::FramelessWindowHint // 无边框
Qt::WindowStaysOnTopHint // 置顶

CMakeLists.txt 模板

cmake_minimum_required(VERSION 3.16)
project(MyQtApp VERSION 1.0 LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)

find_package(Qt6 REQUIRED COMPONENTS Core Gui Widgets Network)

add_executable(MyQtApp
main.cpp
mainwindow.cpp
mainwindow.h
mainwindow.ui
resources.qrc
)

target_link_libraries(MyQtApp PRIVATE
Qt6::Core
Qt6::Gui
Qt6::Widgets
Qt6::Network
)

常用代码片段

显示消息框

QMessageBox::information(this, "标题", "内容");
QMessageBox::warning(this, "警告", "警告内容");
QMessageBox::critical(this, "错误", "错误内容");

if (QMessageBox::question(this, "确认", "确定删除?") == QMessageBox::Yes) {
// 执行删除
}

文件对话框

// 打开文件
QString file = QFileDialog::getOpenFileName(this, "打开", "", "文本 (*.txt)");

// 保存文件
QString file = QFileDialog::getSaveFileName(this, "保存", "", "文本 (*.txt)");

// 选择目录
QString dir = QFileDialog::getExistingDirectory(this, "选择目录");

定时器

// 单次定时器
QTimer::singleShot(1000, this, [=]() {
// 1秒后执行
});

// 重复定时器
QTimer *timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, [=]() {
// 定时执行
});
timer->start(1000); // 每秒触发

JSON 处理

#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>

// 解析 JSON
QString jsonStr = R"({"name": "张三", "age": 25, "skills": ["C++", "Qt"]})";
QJsonDocument doc = QJsonDocument::fromJson(jsonStr.toUtf8());
QJsonObject obj = doc.object();

QString name = obj["name"].toString(); // "张三"
int age = obj["age"].toInt(); // 25
QJsonArray skills = obj["skills"].toArray(); // ["C++", "Qt"]

// 创建 JSON
QJsonObject person;
person["name"] = "李四";
person["age"] = 30;

QJsonArray arr;
arr.append("Python");
arr.append("JavaScript");
person["skills"] = arr;

QJsonDocument newDoc(person);
QString output = newDoc.toJson(QJsonDocument::Indented);

设置存储

#include <QSettings>

// 创建设置对象
QSettings settings("MyCompany", "MyApp");

// 写入设置
settings.setValue("window/size", size());
settings.setValue("window/position", pos());
settings.setValue("user/name", "张三");
settings.setValue("user/remember", true);

// 读取设置
QSize savedSize = settings.value("window/size", QSize(800, 600)).toSize();
QPoint savedPos = settings.value("window/position", QPoint(100, 100)).toPoint();
QString userName = settings.value("user/name", "").toString();
bool remember = settings.value("user/remember", false).toBool();

// 删除设置
settings.remove("user/name");

// 清空所有设置
settings.clear();

文件操作

#include <QFile>
#include <QTextStream>
#include <QFileInfo>

// 读取文本文件
QString readFile(const QString &path)
{
QFile file(path);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
return QString();
}
QTextStream in(&file);
in.setEncoding(QStringConverter::Utf8);
QString content = in.readAll();
file.close();
return content;
}

// 写入文本文件
bool writeFile(const QString &path, const QString &content)
{
QFile file(path);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
return false;
}
QTextStream out(&file);
out.setEncoding(QStringConverter::Utf8);
out << content;
file.close();
return true;
}

// 文件信息
QFileInfo info(path);
QString fileName = info.fileName(); // 文件名
QString basePath = info.path(); // 所在目录
QString suffix = info.suffix(); // 扩展名
qint64 size = info.size(); // 文件大小
bool exists = info.exists(); // 是否存在
bool isDir = info.isDir(); // 是否是目录

目录操作

#include <QDir>

// 创建目录
QDir dir;
if (!dir.exists("mydir")) {
dir.mkdir("mydir");
}

// 创建多级目录
dir.mkpath("path/to/mydir");

// 列出目录内容
QDir dir("mydir");
QStringList files = dir.entryList(QDir::Files); // 文件
QStringList dirs = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot); // 子目录

// 遍历目录(递归)
QDirIterator it("mydir", QDir::Files, QDirIterator::Subdirectories);
while (it.hasNext()) {
QString filePath = it.next();
// 处理文件
}

// 删除目录
dir.removeRecursively(); // 删除目录及其内容

标准路径

#include <QStandardPaths>

QString desktop = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
QString documents = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
QString downloads = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
QString appData = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
QString temp = QStandardPaths::writableLocation(QStandardPaths::TempLocation);

剪贴板操作

#include <QClipboard>
#include <QApplication>

// 获取剪贴板
QClipboard *clipboard = QApplication::clipboard();

// 复制文本
clipboard->setText("复制的文本");

// 粘贴文本
QString text = clipboard->text();

// 复制图片
clipboard->setPixmap(QPixmap(":/images/logo.png"));

// 粘贴图片
QPixmap pixmap = clipboard->pixmap();

进程启动

#include <QProcess>

// 同步执行
QProcess process;
process.start("notepad.exe", QStringList() << "test.txt");
process.waitForFinished();

// 异步执行
QProcess *asyncProcess = new QProcess(this);
connect(asyncProcess, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
this, [](int exitCode, QProcess::ExitStatus status) {
qDebug() << "进程结束,退出码:" << exitCode;
});
asyncProcess->start("ping", QStringList() << "www.baidu.com");

// 读取输出
connect(asyncProcess, &QProcess::readyReadStandardOutput, [=]() {
QString output = asyncProcess->readAllStandardOutput();
qDebug() << output;
});

字符串处理

QString str = "Hello Qt";
str.append("!");
str.prepend("Say: ");

// 格式化
QString formatted = QString("Name: %1, Age: %2").arg("张三").arg(25);

// 分割
QStringList parts = str.split(",");

// 替换
str.replace("old", "new");

容器遍历

// QList
QList<int> list;
for (int value : list) {
qDebug() << value;
}

// QMap
QMap<QString, int> map;
for (auto it = map.begin(); it != map.end(); ++it) {
qDebug() << it.key() << it.value();
}

// C++11 范围 for
for (const auto &key : map.keys()) {
qDebug() << key << map[key];
}

调试技巧

// 输出调试信息
qDebug() << "调试信息";
qWarning() << "警告信息";
qCritical() << "错误信息";

// 输出变量
int value = 42;
qDebug() << "value =" << value;

// 输出容器
QList<int> list = {1, 2, 3};
qDebug() << list;

官方文档链接


QML 常用代码片段

页面导航

// 使用 StackView 进行页面导航
StackView {
id: stackView
initialItem: homePage

Component { id: homePage; HomePage {} }
Component { id: settingsPage; SettingsPage {} }
Component { id: aboutPage; AboutPage {} }
}

// 导航操作
Button {
text: "设置"
onClicked: stackView.push(settingsPage)
}

Button {
text: "返回"
onClicked: stackView.pop()
enabled: stackView.depth > 1
}

Button {
text: "主页"
onClicked: stackView.pop(null) // 返回根页面
}

弹出菜单

// 右键菜单
Item {
TapHandler {
acceptedButtons: Qt.RightButton
onTapped: contextMenu.popup()
}

Menu {
id: contextMenu
MenuItem { text: "复制"; onTriggered: copy() }
MenuItem { text: "粘贴"; onTriggered: paste() }
MenuSeparator {}
MenuItem { text: "删除"; onTriggered: remove() }
}
}

异步加载

// 使用 Loader 延迟加载
Loader {
id: pageLoader
source: ""
asynchronous: true // 异步加载

onLoaded: {
console.log("页面加载完成")
}
}

Button {
text: "加载页面"
onClicked: pageLoader.source = "HeavyPage.qml"
}

// 条件加载
Loader {
source: showDetails ? "DetailsView.qml" : ""
}

颜色工具

// Qt.color 提供颜色工具
Rectangle {
// 十六进制颜色
color: "#FF5722"

// 颜色名称
color: "steelblue"

// RGBA
color: Qt.rgba(1.0, 0.34, 0.13, 1.0)

// HSLA
color: Qt.hsla(0.05, 0.95, 0.55, 1.0)

// 颜色变亮/变暗
color: Qt.lighter("steelblue", 1.2)
color: Qt.darker("steelblue", 1.5)

// 颜色混合
color: Qt.tint("white", "#80FF0000") // 白色带红色调
}

日期时间

// Qt.formatDateTime 提供日期时间格式化
Text {
property var now: new Date()

text: Qt.formatDateTime(now, "yyyy-MM-dd hh:mm:ss")

// 其他格式
// Qt.formatDate(now, "yyyy年MM月dd日")
// Qt.formatTime(now, "hh:mm")

Timer {
interval: 1000
running: true
repeat: true
onTriggered: parent.now = new Date()
}
}

动态创建对象

// 使用 Qt.createComponent 和 createObject
Item {
id: container

function createRectangle() {
var component = Qt.createComponent("MyRectangle.qml")
if (component.status === Component.Ready) {
var rect = component.createObject(container, {
"x": 100,
"y": 100,
"color": "red"
})
}
}

// 使用 incubateObject 异步创建
function createAsync() {
var component = Qt.createComponent("MyRectangle.qml")
var incubator = component.incubateObject(container)

if (incubator.status === Component.Ready) {
console.log("立即创建完成")
} else {
incubator.onStatusChanged = function(status) {
if (status === Component.Ready) {
console.log("异步创建完成")
}
}
}
}
}

网络请求(QML)

import QtQuick

Item {
function fetchData(url) {
var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
console.log("响应:", xhr.responseText)
// 解析 JSON
var data = JSON.parse(xhr.responseText)
processResult(data)
} else {
console.log("错误:", xhr.status)
}
}
}
xhr.open("GET", url)
xhr.send()
}

function postData(url, jsonData) {
var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log("响应:", xhr.responseText)
}
}
xhr.open("POST", url)
xhr.setRequestHeader("Content-Type", "application/json")
xhr.send(JSON.stringify(jsonData))
}
}

本地存储

import QtQuick.LocalStorage 2.0

Item {
// 获取数据库连接
function getDatabase() {
return LocalStorage.openDatabaseSync("MyApp", "1.0", "App Data", 100000)
}

// 初始化表
function initTables() {
var db = getDatabase()
db.transaction(function(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS settings(key TEXT PRIMARY KEY, value TEXT)')
})
}

// 保存设置
function saveSetting(key, value) {
var db = getDatabase()
db.transaction(function(tx) {
tx.executeSql('INSERT OR REPLACE INTO settings VALUES(?, ?)', [key, value])
})
}

// 读取设置
function getSetting(key, defaultValue) {
var db = getDatabase()
var result = defaultValue
db.readTransaction(function(tx) {
var rs = tx.executeSql('SELECT value FROM settings WHERE key = ?', [key])
if (rs.rows.length > 0) {
result = rs.rows.item(0).value
}
})
return result
}

Component.onCompleted: {
initTables()
saveSetting("theme", "dark")
saveSetting("language", "zh_CN")
console.log("主题:", getSetting("theme", "light"))
}
}

国际化速查

C++ 国际化

#include <QTranslator>
#include <QLocale>

// 加载翻译
QTranslator translator;
QString locale = QLocale::system().name(); // 如 "zh_CN"

// 从资源文件加载
if (translator.load(locale, ":/i18n")) {
app.installTranslator(&translator);
}

// 从文件系统加载
if (translator.load(QLocale::system(), "myapp", "_",
app.applicationDirPath() + "/translations")) {
app.installTranslator(&translator);
}

// 标记可翻译字符串
QString text = tr("Hello World"); // QObject 子类中
QString text2 = QCoreApplication::translate("Context", "Hello World"); // 非 QObject 类

// 带参数的翻译
QString msg = tr("File '%1' not found").arg(fileName);

// 复数处理
QString count = tr("%n file(s) found", "", fileCount);

// 消除歧义
QString correct = tr("Right", "correct answer");
QString direction = tr("Right", "direction");

QML 国际化

// 标记可翻译字符串
Text {
text: qsTr("Hello World")
}

// 带参数
Text {
property string name: "张三"
text: qsTr("Hello, %1").arg(name)
}

// 动态切换语言
function switchLanguage(locale) {
// 调用 C++ 的 LanguageManager
LanguageManager.switchLanguage(locale)
}

// 监听语言变化
Connections {
target: LanguageManager
function onLanguageChanged() {
// 重新绑定翻译
title = Qt.binding(function() { return qsTr("My App") })
}
}

翻译工具命令

# 提取可翻译字符串(CMake 项目)
lupdate CMakeLists.txt

# 提取 QML 文件中的字符串
lupdate project.pro

# 编译翻译文件
lrelease translations/*.ts

# 使用 Qt Linguist 编辑
linguist translations/myapp_zh_CN.ts

CMake 配置

# 启用国际化
find_package(Qt6 REQUIRED COMPONENTS LinguistTools)

# 声明支持的语言
qt_standard_project_setup(I18N_TRANSLATED_LANGUAGES de fr zh_CN)

# 自动处理翻译
qt_add_translations(MyApp)

部署速查

Windows 部署

# 自动部署
windeployqt yourapp.exe

# 部署 QML 应用
windeployqt --qmldir C:\path\to\qml yourapp.exe

# 常用选项
windeployqt --release yourapp.exe # Release 版本
windeployqt --dir C:\deploy yourapp.exe # 指定输出目录
windeployqt --translations de,fr yourapp.exe # 指定翻译语言
windeployqt --dry-run yourapp.exe # 模拟运行

Linux 部署

# 查看依赖
ldd yourapp

# 使用 linuxdeployqt 创建 AppImage
./linuxdeployqt yourapp -appimage

# CMake 部署配置
qt_generate_deploy_app_script(TARGET MyApp OUTPUT_SCRIPT deploy_script)
install(SCRIPT ${deploy_script})

macOS 部署

# 创建 .app 包
macdeployqt yourapp.app

# 创建 DMG
macdeployqt yourapp.app -dmg

# 签名
codesign --deep --force --sign "Developer ID Application: Your Name" yourapp.app

# 公证
xcrun notarytool submit yourapp.dmg --apple-id [email protected] --wait
xcrun stapler staple yourapp.dmg

qt.conf 配置

[Paths]
Plugins = plugins
Imports = qml
Translations = translations
Data = .

Qt Installer Framework

<!-- config.xml -->
<Installer>
<Name>我的应用</Name>
<Version>1.0.0</Version>
<Title>安装向导</Title>
<Publisher>公司名称</Publisher>
<TargetDir>@ApplicationsDir@/我的应用</TargetDir>
</Installer>
# 创建安装程序
binarycreator -c config/config.xml -p packages installer.exe

日期时间格式化

#include <QLocale>
#include <QDateTime>

// 本地格式
QLocale locale;
QString dateStr = locale.toString(QDate::currentDate(), QLocale::ShortFormat);
QString timeStr = locale.toString(QTime::currentTime(), QLocale::LongFormat);

// 自定义格式
QString custom = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");

// 货币格式
QString money = locale.toCurrencyString(1234.56); // ¥1,234.56 (中文)

// 数字格式
QString num = locale.toString(1234567.89); // 1,234,567.89 或 1.234.567,89