How to open an existing file using qt?
To open an existing file using Qt, you can choose a file using the QFileDialog::getOpenFileName dialog and get its path, then open the file using QFile::open.
Here is an example code:
#include <QApplication>
#include <QFileDialog>
#include <QFile>
#include <QDebug>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// 打开文件选择对话框并获取文件路径
QString filePath = QFileDialog::getOpenFileName(nullptr, "选择文件", "", "All Files (*.*)");
// 如果用户取消选择文件,则返回空字符串
if (filePath.isEmpty())
return 0;
// 打开文件
QFile file(filePath);
if (!file.open(QIODevice::ReadOnly))
{
qDebug() << "无法打开文件:" << file.errorString();
return 0;
}
// 读取文件内容
QByteArray content = file.readAll();
// 输出文件内容
qDebug() << "文件内容:" << content;
return app.exec();
}
In this example, the file selection dialog is first opened using QFileDialog::getOpenFileName to obtain the path to the chosen file. Then, the file is opened using QFile and checked for successful opening. Finally, the contents of the file are read using QFile::readAll and output to the console using QDebug.