QT记事本的读写函数

头文件:

#include <QMessageBox>

#include <QtDebug>
#include <QFile>
#include <QFileDialog>
#include <QDir>
#include <QTextStream>
 
私有数据成员:
QString fileString;//数据成员,保存要打开的文件名
 
构造函数添加的信号与槽链接:
QObject::connect(ui->openAction,SIGNAL(triggered()),this,SLOT(openFileSlot()));//记事本的打开(O)信号与槽进行连接,openAction是打开(O)的对象名
QObject::connect(ui->saveAction,SIGNAL(triggered()),this,SLOT(saveFileSlot()));//记事本的保存(S)信号与槽进行连接,saveAction是保存(S)的对象名
 
函数:

oid MainWindow::openFileSlot()

{
    fileName = QFileDialog::getOpenFileName(this,"Open File",QDir::currentPath());//获取要打开文件的绝对路径
 
 
    if (fileName.isEmpty())//判断是否为空
    {
        QMessageBox::information(this,"ERROR MESSAGE","Please selete a file");
        return;
    }
    QFile *file = new QFile;
    file->setFileName(fileName);
    bool ok = file->open(QIODevice::ReadOnly);//以只读方式打开文件
    if (ok)
    {
        QTextStream in(file);
        ui->textEdit->setText(in.readAll());//读取文件所有内容
        file->close();
        delete file;
    }
    else
    {
        QMessageBox::warning(this,"ERROR MESSAGE","File Open FiLE"+file->errorString());
        return;
    }
}
 
 
void MainWindow::saveFileSlot()
{
    if (fileName.isEmpty())
    {
        QMessageBox::warning(this,"ERROR MESSAGE","Please selete a file");
        return;
    }
    else
    {
        QFile *file = new QFile;
        file->setFileName(fileName);
        bool ok = file->open(QIODevice::WriteOnly);
 
 
        if (ok)
        {
            QTextStream out(file);
            out << ui->textEdit->toPlainText();
            file->close();
            delete file;
        }
        else
        {
            QMessageBox::information(this,"ERROR MESSAGE","save file error");
            return;
        }
    }
}
 

你可能感兴趣的:(QT记事本的读写函数)