QFile
QTextStream
QMessageBox
QFileDialog
應用示例
mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QFile> #include <QTextStream> #include <QMessageBox> #include <QFileDialog> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } mainwindow.cpp void MainWindow::on_pushButton_2_clicked() { //QFile file("./mytest1.txt"); QFile file("/mnt/hgfs/temp/QFileDemo/mytext.txt"); if(!file.open(QFile::WriteOnly | QFile::Text)){ QMessageBox::warning(this,"title","file not open"); } QTextStream out(&file); QString text= ui->plainTextEdit->toPlainText(); out<<text; file.flush(); file.close(); } void MainWindow::on_pushButton_clicked() { QString filter="All File(*.*);;Text File(*.txt);;xml File(*.xml)"; QString file_name=QFileDialog::getOpenFileName(this,"open a file","/",filter); QFile file(file_name); //QFile file("/mnt/hgfs/temp/QFileDemo/mytext.txt"); if(!file.open(QFile::ReadOnly | QFile::Text)){ QMessageBox::warning(this,"title","file not open"); } QTextStream in(&file); QString text=in.readAll(); ui->plainTextEdit->setPlainText(text); file.close(); }
mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); private slots: void on_pushButton_2_clicked(); void on_pushButton_clicked(); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H