- 参考代码
.h文件
1 #ifndef MYWIDGET_H 2 #define MYWIDGET_H 3 4 #include <QWidget> 5 #include <QFile> 6 #include <QFileDialog> 7 namespace Ui { 8 class myWidget; 9 } 10 11 class myWidget : public QWidget 12 { 13 Q_OBJECT 14 15 public: 16 explicit myWidget(QWidget *parent = 0); 17 ~myWidget(); 18 19 private slots: 20 void on_read_clicked(); 21 22 void on_write_clicked(); 23 24 private: 25 Ui::myWidget *ui; 26 }; 27 28 #endif // MYWIDGET_H
.cpp文件
1 #include "mywidget.h" 2 #include "ui_mywidget.h" 3 4 myWidget::myWidget(QWidget *parent) : 5 QWidget(parent), 6 ui(new Ui::myWidget) 7 { 8 ui->setupUi(this); 9 setWindowTitle("QFile文件读写"); 10 } 11 12 myWidget::~myWidget() 13 { 14 delete ui; 15 } 16 17 void myWidget::on_read_clicked() 18 { 19 QString path = QFileDialog::getOpenFileName(this,"open","../","TXT(*.txt)"); 20 if(path.isEmpty()==false) 21 { 22 QFile file(path); 23 bool isOK = file.open(QIODevice::ReadOnly); 24 if(isOK==true) 25 {//方法1 26 // QByteArray array = file.readAll(); 27 // ui->textEdit->setText(QByteArray(array)); 28 29 QByteArray array;//方法2 30 while(file.atEnd()==false) 31 { 32 array += file.readLine(); 33 } 34 ui->textEdit->setText(array); 35 } 36 file.close(); 37 38 } 39 } 40 41 void myWidget::on_write_clicked() 42 { 43 QString path = QFileDialog::getSaveFileName(this,"save","../","TXT(*.txt)"); 44 if(path.isEmpty()==false) 45 { 46 QFile file; 47 file.setFileName(path); 48 bool isOK = file.open(QIODevice::WriteOnly); 49 if(isOK==true) 50 { 51 QString str = ui->textEdit->toPlainText(); 52 //file.write(str.toUtf8()); 53 file.write(str.toStdString().data()); 54 } 55 file.close(); 56 } 57 58 }