[TOC]

帮助文档的阅读:

Related Non-Members:通常指的是与该类相关的全局函数或其他非成员函数。

Detailed Description :详细描述

基础窗口

  • QWidget:最基础的窗口类,适合创建自定义控件或简单窗口,也即选项框和状态栏。
  • QDialog:用于创建对话框,适合短暂的用户交互,也即弹窗。

​ 右键IDE的项目文件夹、add new、选择QT并添加对应窗口、在主窗口头文件中引入新窗口文件、在主窗口类中添加 指向新窗口的指针、在组件的槽函数中创建对象、显示新窗口。

1
2
3
4
5
if(!dialog_ui)
{
dialog_ui = new QDialog(this);
dialog_ui->show();
}
  • QMainWindow:用于创建主应用程序窗口,适合复杂的应用程序界面。

窗口的基本操作

窗口的移动

基础组件

  • QButton:按钮类,常见方法为
  • QText:用于创建对话框,适合短暂的用户交互,也即弹窗。
  • QMainWindow:用于创建主应用程序窗口,适合复杂的应用程序界面。

QT封装的数据流

QDebug类中重载了<<,故cout不可用转用qDebug()<<”hello”<<endl;

Qt中的类型QtGlobal(基础类型,主要实现32bit和64bit系统的统一)QByteArray(多功能的动态数组)Qstring(字符串类)QPoint(坐标)QTime(时间)QData(日期)

QByteArray 是 Qt 框架中的一个类,用于存储和操作字节数组。它提供了一个方便的接口来处理原始数据、编码转换以及串行化等任务。以下是 QByteArray 的一些主要特点和用途:

  1. 动态数组(addend):QByteArray 自动增长以容纳其内容,允许你轻松地添加或移除数据。

  2. 二进制安全:它可以用来存储任意的二进制数据,包括空字符(’\0’),这使得它非常适合用于网络传输、文件I/O等场景。

  3. 丰富的API:提供了大量的成员函数用于搜索、替换、截取子数组、转换大小写等操作。

  4. 与QString互转:可以非常方便地在 QByteArrayQString 之间进行转换,支持不同的文本编码(如 UTF-8, Latin1 等)。

  5. 优化的内存使用:对于小的字节数组,QByteArray 可能会使用共享的数据缓冲区来节省内存。

  6. 数值与字节序列转换:支持将数字类型(如 int, float 等)转换为字节序列,反之亦然,这对串行化对象或网络通信特别有用。

  7. 十六进制编码/解码:可以直接对数据进行十六进制编码或解码,便于调试或特定格式的数据传输。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{
QString string = "hello";

// 创建一个空的 QByteArray
QByteArray byteArray;

// 使用 append 方法添加数据
byteArray.append(string.toUtf8());

qDebug()<<byteArray<<endl;



int index =byteArray.indexOf("ll");//查找字符串位置
if(index!=-1)
{
qDebug()<<index<<endl;
}
QString fromUtf8String = QString::fromUtf8(byteArray);
qDebug()<<fromUtf8String<<endl;


}

对象树

在Qt中,对象树(Object Tree) 是一种管理对象(特别是 QObject 及其派生类对象)生命周期的机制。通过对象树,Qt 可以自动管理对象的创建和销毁,避免内存泄漏等问题。对象树可以用于同步主窗口与弹窗的生命周期


对象树的使用

  1. 对象树的构建

    • 通过 QObject 的构造函数或 setParent() 方法,可以指定一个对象的父对象。

      1
      2
      QObject *parent = new QObject();
      QObject *child = new QObject(parent); // child 的父对象是 parent
  2. 对象树的销毁

    • 当父对象被销毁时,Qt 会自动递归销毁其所有子对象。

      1
      delete parent; // 会自动销毁 child

对象树的示例

以下是一个简单的对象树示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <QObject>
#include <QDebug>

class MyObject : public QObject {
public:
MyObject(const QString &name, QObject *parent = nullptr)
: QObject(parent), m_name(name) {
qDebug() << "Created:" << m_name;
}

~MyObject() {
qDebug() << "Destroyed:" << m_name;
}

private:
QString m_name;
};

int main() {
MyObject *parent = new MyObject("Parent");
MyObject *child1 = new MyObject("Child 1", parent);
MyObject *child2 = new MyObject("Child 2", parent);

delete parent; // 会自动销毁 child1 和 child2
return 0;
}

输出

1
2
3
4
5
6
Created: Parent
Created: Child 1
Created: Child 2
Destroyed: Parent
Destroyed: Child 1
Destroyed: Child 2

Qt 的对象树机制通过父子关系自动管理对象的生命周期,简化了内存管理,同时提供了层次化结构和事件传递的基础。理解对象树是掌握 Qt 编程的重要一步。

信号与信号槽

在Qt框架中,信号与槽(Signals and Slots)是一种用于对象间通信的机制。这种机制是Qt的核心特性之一,允许对象在特定事件发生时发送信号,而其他对象可以通过槽来接收并处理这些信号。

信号(Signals)

  • 定义:信号是Qt对象在特定事件发生时发出的通知。例如,按钮被点击时,按钮对象会发出一个clicked()信号。
  • 特点
    • 信号没有实现代码,只有声明。
    • 信号可以带有参数,这些参数可以在发出信号时传递给槽。
    • 信号可以连接到多个槽,也可以连接到其他信号。

槽(Slots)

  • 定义:槽是普通的成员函数,用于响应特定信号。当信号发出时,与之连接的槽会被自动调用。@\n快速创建槽函数。
  • 特点
    • 槽可以有实现代码,用于处理信号。
    • 槽可以带有参数,这些参数由信号传递。
    • 槽可以是任何可调用的函数,包括普通成员函数、静态函数、lambda表达式等。

连接信号与槽

  • 连接方式:使用QObject::connect函数将信号与槽连接起来。连接后,当信号发出时,槽会自动被调用。
  • 语法
    1
    QObject::connect(sender, &SenderClass::signal, receiver, &ReceiverClass::slot);
    • sender:发出信号的对象。
    • signal:信号的地址。
    • receiver:接收信号的对象。
    • slot:槽的地址。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <QApplication>
#include <QPushButton>
#include <QMessageBox>

class MyWidget : public QWidget {
Q_OBJECT

public:
MyWidget(QWidget *parent = nullptr) : QWidget(parent) {
QPushButton *button = new QPushButton("Click me", this);
connect(button, &QPushButton::clicked, this, &MyWidget::showMessage);
}

public slots:
void showMessage() {
QMessageBox::information(this, "Message", "Button clicked!");
}
};

int main(int argc, char *argv[]) {
QApplication app(argc, argv);
MyWidget widget;
widget.show();
return app.exec();
}
  • 信号QPushButton::clicked()是按钮被点击时发出的信号。
  • MyWidget::showMessage()是一个槽函数,用于显示消息框。
  • 连接:使用connect函数将按钮的clicked()信号连接到MyWidgetshowMessage()槽。

常用类

QTimer

在Qt框架中,QTimer 类是一个用于定时器功能的工具类。它允许你在指定的时间间隔内触发事件或执行代码。QTimer 是 Qt 中实现定时任务的核心类,广泛应用于需要周期性执行任务的场景,例如更新 UI、轮询数据、动画等。

QTimer 的基本功能

  1. 单次定时器
    • 定时器只触发一次,执行一次任务后停止。
  2. 周期性定时器
    • 定时器以固定的时间间隔重复触发,直到手动停止。
  3. 高精度定时器
    • 提供毫秒级的时间精度,适用于需要精确控制的场景。

QTimer 的主要成员函数

以下是 QTimer 类中常用的成员函数:

  1. start(int msec)

    • 启动定时器,参数 msec 是时间间隔(以毫秒为单位)。
    • 如果是单次定时器,定时器会在 msec 毫秒后触发一次;如果是周期性定时器,则会每隔 msec 毫秒触发一次。
  2. stop()

    • 停止定时器,不再触发。
  3. setInterval(int msec)

    • 设置定时器的时间间隔(以毫秒为单位)。
  4. interval()

    • 返回当前定时器的时间间隔。
  5. isActive()

    • 判断定时器是否正在运行。
  6. setSingleShot(bool singleShot)

    • 设置定时器是否为单次触发。如果 singleShottrue,则定时器只触发一次;否则会周期性触发。
  7. timerId()

    • 返回定时器的 ID,可以用于识别定时器。

QTimer 的信号

QTimer 类提供了一个信号:

  • timeout()
    • 当定时器超时时,会发出此信号。通常将此信号连接到槽函数,以执行定时任务。

使用 QTimer 的步骤

  1. 创建 QTimer 对象。
  2. 设置定时器的时间间隔和触发模式(单次或周期性)。
  3. timeout() 信号连接到槽函数。
  4. 启动定时器。

示例代码

以下是一个简单的示例,展示如何使用 QTimer 实现周期性任务:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <QCoreApplication>
#include <QTimer>
#include <QDebug>

class MyClass : public QObject {
Q_OBJECT

public:
MyClass(QObject *parent = nullptr) : QObject(parent) {
// 创建定时器
timer = new QTimer(this);

// 设置定时器时间间隔为 1000 毫秒(1 秒)
timer->setInterval(1000);

// 连接 timeout() 信号到槽函数
connect(timer, &QTimer::timeout, this, &MyClass::onTimeout);

// 启动定时器
timer->start();
}

public slots:
void onTimeout() {
qDebug() << "Timer triggered at:" << QTime::currentTime().toString();
}

private:
QTimer *timer;
};

int main(int argc, char *argv[]) {
QCoreApplication app(argc, argv);

MyClass myObject;

return app.exec();
}

代码解释

  1. 定时器创建
    • QTimer *timer = new QTimer(this); 创建一个 QTimer 对象。
  2. 设置时间间隔
    • timer->setInterval(1000); 设置定时器每隔 1 秒触发一次。
  3. 连接信号与槽
    • connect(timer, &QTimer::timeout, this, &MyClass::onTimeout);timeout() 信号连接到 onTimeout() 槽函数。
  4. 启动定时器
    • timer->start(); 启动定时器。
  5. 槽函数
    • onTimeout() 是定时器触发时执行的槽函数,输出当前时间。

单次定时器示例

如果你只需要定时器触发一次,可以使用 setSingleShot(true)

1
2
3
4
5
6
7
QTimer *timer = new QTimer(this);
timer->setInterval(5000); // 5 秒后触发
timer->setSingleShot(true); // 设置为单次触发
connect(timer, &QTimer::timeout, this, []() {
qDebug() << "Single-shot timer triggered!";
});
timer->start();

注意事项

  1. 线程安全
    • QTimer 依赖于事件循环,因此在多线程中使用时需要注意线程的上下文。
  2. 精度问题
    • 定时器的精度取决于操作系统和系统负载,可能无法保证绝对的毫秒级精度。
  3. 资源消耗
    • 如果定时器间隔过短(如几毫秒),可能会导致 CPU 占用率过高。

总结

QTimer 是 Qt 中实现定时任务的核心工具,使用简单且功能强大。通过信号与槽机制,可以轻松实现周期性任务或单次延迟任务。无论是更新 UI、轮询数据,还是实现动画效果,QTimer 都是一个非常实用的工具。

作业一:登录窗口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include "clidnwindow.h"
#include "ui_clidnwindow.h"
#include "mainwindow.h"

clidnWindow::clidnWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::clidnWindow)
{
ui->setupUi(this);
// 移除窗口边框
this->setWindowFlags(Qt::FramelessWindowHint);

// 设置窗口大小
this->setFixedSize(300, 400);

// 创建一个 QWidget 作为中央部件
QWidget *centralWidget = new QWidget(this);
this->setCentralWidget(centralWidget);

// 添加控件
QLabel *labelUsername = new QLabel("用户名:", centralWidget);
QLineEdit *lineEditUsername = new QLineEdit(centralWidget);
QLabel *labelPassword = new QLabel("密码:", centralWidget);
QLineEdit *lineEditPassword = new QLineEdit(centralWidget);
lineEditPassword->setEchoMode(QLineEdit::Password); // 设置密码输入框为密码模式
QPushButton *buttonLogin = new QPushButton("登录", centralWidget);

// 布局设置
QVBoxLayout *layout = new QVBoxLayout(centralWidget);
layout->addWidget(labelUsername);
layout->addWidget(lineEditUsername);
layout->addWidget(labelPassword);
layout->addWidget(lineEditPassword);
layout->addWidget(buttonLogin);

// 设置布局的间距和对齐方式
layout->setSpacing(10); // 设置控件之间的间距
layout->setAlignment(Qt::AlignCenter); // 设置控件居中对齐

QAction *m_Action_1;
QAction *m_Action_2;
QAction *m_Action_3;
QAction *m_Action_4;
//右键菜单栏
m_Action_1 = new QAction("移动" , this);
m_Action_2 = new QAction("最小" , this);
m_Action_3 = new QAction("关闭" , this);


QMenu *m_menu;

m_menu = new QMenu(this);

m_menu->addAction(m_Action_1);
m_menu->addAction(m_Action_2);
m_menu->addAction(m_Action_3);


this->setContextMenuPolicy(Qt::CustomContextMenu);

// 抓右键点击信号
connect( this , &QWidget::customContextMenuRequested , this , [=](const QPoint &pos){
qDebug() << "右键点击了窗口" << pos;
// 右键启动一个菜单
QPoint pos_m_menu =pos + this->pos();
m_menu->exec(pos_m_menu);

});
connect(m_Action_1,&QAction::triggered,this,[=](){
qDebug()<<"Action2 ok"<<endl;
});
connect(m_Action_2,&QAction::triggered,this,&QWidget::showMinimized);

connect(m_Action_3,&QAction::triggered,this,&QWidget::close);


centralWidget->setLayout(layout);
}
clidnWindow::~clidnWindow()
{
delete ui;
}

1. 使用 Qt Designer 创建下拉列表

如果你使用 Qt Designer 或 Qt Creator 的 UI 设计器,可以按照以下步骤创建下拉列表:

  1. 打开 .ui 文件。
  2. 在控件工具箱中找到 QComboBox 控件。
  3. 将其拖放到你的窗口或对话框中。
  4. 右键点击 QComboBox,选择 Edit Items,在弹出的对话框中添加选项(如 “Option 1”, “Option 2”, “Option 3”)。
  5. 保存 .ui 文件并重新编译项目。

2. 在代码中创建下拉列表

如果你更喜欢在代码中创建下拉列表,可以使用以下方法:

步骤 1:包含头文件

1
#include <QComboBox>

步骤 2:创建 QComboBox 并添加选项

1
2
3
4
5
6
7
8
9
10
11
12
// 创建 QComboBox 对象
QComboBox *comboBox = new QComboBox(this);

// 添加选项
comboBox->addItem("Option 1");
comboBox->addItem("Option 2");
comboBox->addItem("Option 3");

// 将 QComboBox 添加到布局中
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(comboBox);
setLayout(layout);

步骤 3:处理选项选择事件

你可以连接 QComboBoxcurrentIndexChanged 信号到一个槽函数,以处理用户选择的变化:

1
2
3
4
5
6
7
8
// 在构造函数中连接信号和槽
connect(comboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &MainWindow::onComboBoxIndexChanged);

// 槽函数实现
void MainWindow::onComboBoxIndexChanged(int index) {
qDebug() << "Selected index:" << index;
qDebug() << "Selected text:" << comboBox->itemText(index);
}


3. 常用功能

以下是一些 QComboBox 的常用功能和用法:

添加选项

1
2
comboBox->addItem("New Option");
comboBox->addItems(QStringList() << "Option A" << "Option B" << "Option C");

设置默认选项

1
comboBox->setCurrentIndex(1); // 设置第二个选项为默认选项

获取当前选中的选项

1
2
int index = comboBox->currentIndex(); // 获取当前选中的索引
QString text = comboBox->currentText(); // 获取当前选中的文本

删除选项

1
comboBox->removeItem(1); // 删除第二个选项

清空所有选项

1
comboBox->clear();

禁用下拉列表

1
comboBox->setEnabled(false); // 禁用下拉列表

4. 高级功能

设置可编辑的下拉列表

1
comboBox->setEditable(true); // 允许用户输入自定义值

设置占位符文本

1
comboBox->setPlaceholderText("Please select an option");

添加图标到选项

1
comboBox->addItem(QIcon(":/images/icon.png"), "Option with Icon");

自定义数据

你可以为每个选项附加自定义数据:

1
2
3
4
5
6
7
comboBox->addItem("Option 1", QVariant(100));
comboBox->addItem("Option 2", QVariant(200));
comboBox->addItem("Option 3", QVariant(300));

// 获取当前选项的自定义数据
QVariant data = comboBox->currentData();
qDebug() << "Custom data:" << data.toInt();


5. 完整示例

以下是一个完整的示例,展示如何在 Qt 中创建并使用下拉列表:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <QApplication>
#include <QComboBox>
#include <QHBoxLayout>
#include <QDebug>
#include <QWidget>

class MainWindow : public QWidget {
Q_OBJECT

public:
MainWindow(QWidget *parent = nullptr) : QWidget(parent) {
// 创建 QComboBox
QComboBox *comboBox = new QComboBox(this);
comboBox->addItem("Option 1");
comboBox->addItem("Option 2");
comboBox->addItem("Option 3");

// 连接信号和槽
connect(comboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &MainWindow::onComboBoxIndexChanged);

// 设置布局
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(comboBox);
setLayout(layout);
}

private slots:
void onComboBoxIndexChanged(int index) {
qDebug() << "Selected index:" << index;
}
};

int main(int argc, char *argv[]) {
QApplication app(argc, argv);
MainWindow window;
window.show();
return app.exec();
}

#include "main.moc"


总结

在 Qt 中,QComboBox 是实现下拉列表的标准控件。你可以通过 Qt Designer 快速创建下拉列表,也可以在代码中动态创建和管理。QComboBox 提供了丰富的功能,如添加选项、处理选择事件、设置自定义数据等,非常适合用于需要用户从预定义选项中选择的场景。

在 Qt 中,QTextEdit 是一个用于显示和编辑多行文本的控件。要获取 QTextEdit 中的文本,可以使用以下方法:


1. 获取纯文本

使用 toPlainText() 方法可以获取 QTextEdit 中的纯文本内容(不带任何格式)。

示例:

1
2
QString text = ui->textEdit->toPlainText();
qDebug() << "Text content:" << text;

2. 获取带格式的文本

使用 toHtml() 方法可以获取 QTextEdit 中的带格式文本(HTML 格式)。

示例:

1
2
QString htmlText = ui->textEdit->toHtml();
qDebug() << "HTML content:" << htmlText;

3. 获取选中的文本

使用 textCursor() 方法可以获取当前光标对象,然后通过 selectedText() 方法获取选中的文本。

示例:

1
2
3
QTextCursor cursor = ui->textEdit->textCursor();
QString selectedText = cursor.selectedText();
qDebug() << "Selected text:" << selectedText;

4. 获取段落文本

如果需要获取特定段落的文本,可以使用 QTextCursor 遍历段落。

示例:

1
2
3
4
5
6
7
QTextDocument *document = ui->textEdit->document();
QTextCursor cursor(document);

for (QTextBlock block = document->begin(); block != document->end(); block = block.next()) {
QString paragraphText = block.text();
qDebug() << "Paragraph text:" << paragraphText;
}

5. 完整示例

以下是一个完整的示例,展示如何获取 QTextEdit 中的文本内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <QApplication>
#include <QTextEdit>
#include <QPushButton>
#include <QVBoxLayout>
#include <QDebug>
#include <QWidget>

class MainWindow : public QWidget {
Q_OBJECT

public:
MainWindow(QWidget *parent = nullptr) : QWidget(parent) {
// 创建 QTextEdit
textEdit = new QTextEdit(this);
textEdit->setPlainText("Hello, this is a QTextEdit example.");

// 创建按钮
QPushButton *button = new QPushButton("Get Text", this);

// 连接按钮点击信号到槽函数
connect(button, &QPushButton::clicked, this, &MainWindow::onButtonClicked);

// 设置布局
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(textEdit);
layout->addWidget(button);
setLayout(layout);
}

private slots:
void onButtonClicked() {
// 获取纯文本
QString plainText = textEdit->toPlainText();
qDebug() << "Plain text:" << plainText;

// 获取带格式的文本
QString htmlText = textEdit->toHtml();
qDebug() << "HTML text:" << htmlText;

// 获取选中的文本
QTextCursor cursor = textEdit->textCursor();
QString selectedText = cursor.selectedText();
qDebug() << "Selected text:" << selectedText;
}

private:
QTextEdit *textEdit;
};

int main(int argc, char *argv[]) {
QApplication app(argc, argv);
MainWindow window;
window.show();
return app.exec();
}

#include "main.moc"

6. 总结

  • toPlainText(): 获取纯文本内容。
  • toHtml(): 获取带格式的 HTML 文本。
  • textCursor().selectedText(): 获取选中的文本。
  • QTextDocumentQTextCursor: 用于遍历和操作文本内容。

通过这些方法,你可以轻松获取 QTextEdit 中的文本内容,并根据需要进行处理。

在Qt中,保存文件通常涉及到使用 QFileDialog 来获取用户想要保存的文件路径和文件名,并且可能需要根据文件类型决定如何处理数据。以下是一个简单的示例,演示了如何使用 QFileDialog::getSaveFileName 方法来实现文件保存功能。

示例代码

假设你正在开发一个应用程序,并希望添加一个“保存”功能,允许用户选择保存位置并将一些文本内容保存到文件中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <QFileDialog>
#include <QMessageBox>
#include <QFile>
#include <QTextStream>

void saveFile() {
// 弹出文件对话框,让用户选择保存位置和输入文件名
QString fileName = QFileDialog::getSaveFileName(nullptr,
"保存文件",
QDir::homePath(),
"文本文件 (*.txt);;所有文件 (*)");

if (fileName.isEmpty()) {
// 用户取消了对话框或未指定文件名
return;
}

// 创建文件对象并打开以供写入
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
// 如果文件无法打开,则显示错误信息
QMessageBox::warning(nullptr, "保存文件", "无法保存文件: " + file.errorString());
return;
}

// 假设我们有一个QString变量textData包含要保存的数据
QString textData = "这是要保存到文件的文本内容。\n";

// 使用QTextStream将数据写入文件
QTextStream out(&file);
out << textData;

// 关闭文件
file.close();

// 可选:显示保存成功的消息
QMessageBox::information(nullptr, "保存文件", "文件已成功保存");
}

说明

  1. QFileDialog::getSaveFileName:此静态函数用于显示一个对话框,允许用户选择保存文件的位置和名称。它返回用户选择的文件路径作为 QString。如果用户取消了对话框,则返回一个空字符串。

  2. QFile 和 QTextStreamQFile 类用于读写文件,而 QTextStream 提供了一种方便的方式来读取和写入文本数据。在这个例子中,我们创建了一个 QTextStream 对象并将数据写入文件。

  3. 错误处理:检查文件是否成功打开非常重要。如果文件无法打开(例如由于权限问题),则向用户显示一条错误消息。

  4. 关闭文件:完成文件写入后,记得调用 close() 方法来关闭文件。虽然当 QFile 对象被销毁时会自动关闭文件,但显式地关闭是一个好的实践。

这个示例展示了如何保存纯文本文件,但对于其他类型的文件(如图片、音频等),你需要相应地调整写入逻辑。例如,对于二进制文件,你可以直接使用 QFilewrite() 方法而不使用 QTextStream