QT 通过QFileDialog选择一个txt文件并打开
作者:互联网
(1) 首先需要包含头文件
#include "QFileDialog"
#include "QDebug"
(2) 实际代码
void MainWindow::on_pushButton_clicked()
{
QStringList infoList;
//获取文件名
QString fileName = QFileDialog::getOpenFileName(
this,
tr("open a file."),
"",
tr("text(*.txt);;video files(*.avi *.mp4 *.wmv);;All files(*.*)"));
if (fileName.isEmpty())
{
QMessageBox::warning(this, "Warning!", "Failed to open the video!");
}
else
{
QFile file(fileName);
//打开文件
if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug()<<"Can't open the file!"<<endl;
}
//循环读取txt 并打印
while(!file.atEnd())
{
QByteArray line = file.readLine();
QString str(line);
if(str.contains("\n"))
{
str = str.replace("\n" , "");
}
qDebug()<< str;
}
}
}
标签:file,QT,fileName,QFileDialog,str,txt,open 来源: https://blog.csdn.net/qq_14874791/article/details/106372472