Qt大作业————记事本——Day3

今天做的是文件的新建 打开 保存 另存为

 

//新建
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());
}

                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值