1.文件的基本操作:
读写
2.文件对话框:
QFileDialog
3.文件列表控制框
listwidget
假设想通过双击打开文件
步骤如下:
1.在Listwidget中双击转到槽函数
2.获取当前点击文件的文件名
QString filename=ui->listWidget->currentItem()->text();//获取列表窗口的数据内容
返回值:filename只是文件名,并没有路径,所有要想打开该文件,还需拼接路径
3.拼接路径:
QString filepath=Dir;//Dir是我们打开目录对话框获取到目录的路径
filepath.append("/").append(filename);//拼接路径和文件名
4.打开文件,读取数据
QFile file(filepath);//依据路径构造文件对象
bool isopen= file.open(QIODevice::ReadWrite);
if(isopen)
{
QByteArray readdate= file.readAll();
ui->textEdit->setText(readdate);//显示到textEDIt控件上
}
else
{
qDebug()<<"打开错误";
}
4.文件只读控件
text browser
5.文件编辑控件
text edit
6.文件类
QFile
1.构造文件对象
2.打开文件
一般选择这个简单点
The file is opened with open(), closed with close(), and flushed with flush(). Data is usually read and written using QDataStream or QTextStream, but you can also call the QIODevice-inherited functions read(), readLine(), readAll(), write(). QFile also inherits getChar(), putChar(), and ungetChar(), which work one character at a time.
这段话翻译过来就是:
文件用open()打开,用close()关闭,用flush()刷新。通常使用QDataStream或QTextStream读取和写入数据,但也可以调用QIODevice继承的函数read()、readLine()、readAll()、write()。QFile还继承getChar()、putChar()和ungetChar(),它们一次只能使用一个字符。
所以:
1.我们如果想要打开文件用open,关闭用close,刷新用flush
2.读取数据和写数据使用QDataStream或QTextStream或者直接使用QIODevice
7.目录类
QDir
1.打开目录对话框:
QString dirpath=QFileDialog::getExistingDirectory(this,"选择文件","./");
返回值:是打开目录的路径
2.依据打开目录的返回值构造对象对象
QDir dir(dirpath);//依据文件目录构造目录对象
3.获取目录里面的所有文件并显示在列表窗口
QStringList dirnamelist= dir.entryList();//获取目录里的所有文件
ui->listWidget->clear();
ui->listWidget->addItems(dirnamelist);//把所有文件加到列表窗口