3.5
实现文件打开功能
3.5.1
开发流程
为
QPushButton
对应
Open
的控件设置槽函数
槽函数代码开发
打开文件
读取文件
把文件数据显示在
TextEdit
控件上
3.5.2
代码实现
void
Widget::on_btnFileOpen_clicked
()
{
QString fileName
=
QFileDialog::getOpenFileName
(
this
,
tr
(
"Open File"
),
"D:/QT/"
,
tr
(
"Text (*.txt)"
));
ui
->
textEdit
->
clear
();
file
.
setFileName
(
fileName
);
if
(
!
file
.
open
(
QIODevice::ReadOnly
|
QIODevice::Text
)){
qDebug
()
<<
"file open error"
;
}
QTextStream in
(
&
file
);
in
.
setCodec
(
"UTF-8"
);
while
(
!
in
.
atEnd
()){
QString context
=
in
.
readLine
();
// qDebug() << qPrintable(context);
// ui->textEdit->setText(context);
ui
->
textEdit
->
append
(
context
);
}
}
3.5.3
打开功能优化
字符编码相关问题解决
在
Qt
中,
QTextStream
常用的字符编码主要包括以下几种:

这些编码覆盖了大部分常用的语言字符集,可以通过
QTextCodec::codecForName()
方法在
QTextStream
中进行设置。
检测光标位置,并在右下角显示光标位置。
在程序左上方显示当前打开的文件名称。
3.5.4 QComboBox
QComboBox
是
Qt
框架中用于创建下拉列表的一个控件。
它允许用户从一组选项中选择一个选项,并可以配置为可编辑,使用户能够在其中输入文本。
QComboBox
提供了一系列方法来添加、删除和修改列表中的项,支持通过索引或文本检索项,并可以通过信号和槽机制来响应用户的选择变化。该控件广泛应用于需要从多个选项中进行选择的用户界面场景,例如表单和设置界面。

示例代码
#include <QComboBox>
#include <QVBoxLayout>
#include <QWidget>
class
ComboBoxDemo
:
public
QWidget
{
Q_OBJECT
public
:
ComboBoxDemo
() {
QComboBox
*
comboBox
=
new
QComboBox
(
this
);
comboBox
->
addItems
({
"
选项
1"
,
"
选项
2"
,
"
选项
3"
});
comboBox
->
setEditable
(
true
);
connect
(
comboBox
,
SIGNAL
(
currentIndexChanged
(
int
)),
this
,
SLOT
(
onSelectionChanged
(
int
)));
QVBoxLayout
*
layout
=
new
QVBoxLayout
(
this
);
layout
->
addWidget
(
comboBox
);
}
private
slots
:
void
onSelectionChanged
(
int
index
) {
// 当选中的项改变时的处理逻辑
}
};
这个示例展示了
QComboBox
的基本用法,包括添加选项、设置为可编辑以及连接信号和槽。您可以根据需要调整和扩展这个示例。
3.5.5
记事本支持字符编码
获取用户在
QComboBox
上选择的字符编码,用特定编码打开文件,这里注意
QComboBox
返回
QString类型,setCodec参数要求
const char*
型。
QString
先转成
C++
的
String
,再转换成
const char*。
void
Widget::on_btnFileOpen_clicked
()
{
// 使用文件对话框获取要打开的文件的路径
QString fileName
=
QFileDialog::getOpenFileName
(
this
,