Qt snippet — 打开文件&保存文件

打开文件:

 1 void Notepad::on_actionOpen_triggered()
 2 {
 3     QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), QString(),
 4             tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));
 5 
 6         if (!fileName.isEmpty()) {
 7             QFile file(fileName);
 8             if (!file.open(QIODevice::ReadOnly)) {
 9                 QMessageBox::critical(this, tr("Error"), tr("Could not open file"));
10                 return;
11             }
12             QTextStream in(&file);
13             ui->textEdit->setText(in.readAll());
14             file.close();
15         }
16 }

保存文件:

 1 void Notepad::on_actionSave_triggered()
 2 {
 3             QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), QString(),
 4             tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));
 5 
 6             if (!fileName.isEmpty()) {
 7                 QFile file(fileName);
 8                 if (!file.open(QIODevice::WriteOnly)) {
 9                     // error message
10                 } else {
11                     QTextStream stream(&file);
12                     stream << ui->textEdit->toPlainText();
13                     stream.flush();
14                     file.close();
15                 }
16             }
17 }

 

posted on 2013-08-02 21:16  铁树银花  阅读(1537)  评论(0编辑  收藏  举报

导航