今天做的是文件的新建 打开 保存 另存为
//新建
void MainWindow::on_actionNew_triggered()
{
ui->TextEdit->clear();
this->setWindowTitle(tr("新建文本文件"));
}
//打开
void MainWindow::on_actionOpen_triggered()
{
QString filename = QFileDialog::getOpenFileName(this,"打开文件",".",
tr("Text files (*.txt);; ALL(*.*)"));
QFile file(filename);
//判断是否打开文件
if(!file.open(QFile::ReadOnly | QFile::Text)){
return;
}
filePath = filename;
QTextStream in(&file);
QString text = in.readAll();
ui->TextEdit->insertPlainText(text);
file.close();
this->setWindowTitle(QFileInfo(filename).absoluteFilePath());
}
//保存
void MainWindow::on_actionSave_triggered()
{
QFile file(filePath);
//判断是否打开
if(!file.open(QFile::WriteOnly | QFile::Text)){
QString filename = QFileDialog::getSaveFileName(this,"保存文件",".",
tr("Text files (*.txt);; ALL(*.*)"));
QFile file(filename);
if(!file.open(QFile::WriteOnly | QFile::Text)){
return;
}
filePath = filename;
}
QTextStream out(&file);
QString text = ui->TextEdit->toPlainText();
out<<text;
file.flush();
file.close();
this->setWindowTitle(QFileInfo(filePath).absoluteFilePath());
}
//另存为
void MainWindow::on_actionSaveAs_triggered()
{
QString filename = QFileDialog::getSaveFileName(this,"保存文件",".",
tr("Text files (*.txt);; ALL(*.*)"));
QFile file(filename);
//判断是否打开文件
if(!file.open(QFile::WriteOnly | QFile::Text)){
return;
}
filePath = filename;
QTextStream out(&file);
QString text = ui->TextEdit->toPlainText();
out<<text;
file.flush();
file.close();
this->setWindowTitle(QFileInfo(filePath).absoluteFilePath());
}