一步步学Qt,第四天-Qt 建立MainWindow的小小bug处理
一步步学Qt,第四天-Qt 建立MainWindow的小小bug处理
刚写好的小小的记事本,差不多可以使用了,不过在测试中发现了很多的bug,这才一个个的修改了,修改后的实现文件code是:
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QMessageBox> #include <QFileDialog> #include <QTextStream> #include <QTextEdit> #include <QDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); setCentralWidget(ui->textEdit); //action setting ui->mainToolBar->addAction(ui->action_New); ui->mainToolBar->addAction(ui->action_Open); ui->mainToolBar->addAction(ui->action_Cut); ui->mainToolBar->addAction(ui->action_About); //slot setting connect(ui->action_About,SIGNAL(triggered()),this,SLOT(about())); connect(ui->action_New,SIGNAL(triggered()),this,SLOT(newFile())); connect(ui->action_Open,SIGNAL(triggered()),this,SLOT(openFile())); } MainWindow::~MainWindow() { delete ui; } void MainWindow::about() { QMessageBox::about(this,tr("About this app"),tr("copyrigth by PowerLinux")); return; } void MainWindow::newFile() { int i = fileChanged(); if(i == 1){ int s = QMessageBox::question(this,tr("Asking"),tr("File is changed ,Save it?"),QMessageBox::Ok | QMessageBox::Cancel); if(s == QMessageBox::Ok){ saveFile(); ui->textEdit->setText(""); } else{ ui->textEdit->setText(""); } } else{ MainWindow *newWin = new MainWindow; newWin->show(); } } void MainWindow::openFile() { int i = fileChanged(); if(i == 1){ fileName = QFileDialog::getOpenFileName(this); QString openfilename = fileName; if(!fileName.isEmpty()) { int s = QMessageBox::question(this,tr("Asking"),tr("the old File is changed ,are you sure?"),QMessageBox::Ok | QMessageBox::Cancel); if(s == QMessageBox::Ok){ saveFile(); ui->textEdit->setText(""); loadFile(openfilename); } if(s == QMessageBox::Cancel){ ui->textEdit->setText(""); loadFile(openfilename); } } } else{ fileName = QFileDialog::getOpenFileName(this); if (!fileName.isEmpty()) { loadFile(fileName); } } } void MainWindow::loadFile(QString filename){ QFile file(filename); if(file.open(QIODevice::ReadOnly | QIODevice::Text)){ QTextStream textStream(&file); while(!textStream.atEnd()){ ui->textEdit->append(textStream.readLine()); } } } int MainWindow::fileChanged(){ if(ui->textEdit->document()->isModified()){ return 1; } else{ return 0; } } void MainWindow::saveFile() //! [44] //! [45] { fileName = QFileDialog::getSaveFileName(this); if (!fileName.isEmpty()){ QFile file(fileName); if (!file.open(QFile::WriteOnly | QFile::Text)) { QMessageBox::warning(this, tr("Application"), tr("Cannot write file %1:\n%2.") .arg(fileName) .arg(file.errorString())); } else{ QTextStream out(&file); out << ui->textEdit->toPlainText(); } } }
注意code中
QString openfilename = fileName;openfilename是一个临时使用的数据,为了是在getOpenFileName的时候不会与在使用saveFile时与对应的fileName不会重复,这样在loadfile就不会出错了.