Qt学习笔记之日记本(文本编辑器)

本文介绍了一个基于Qt的桌面日记编辑器应用,集成了文本编辑、格式调整、日期选择等功能,支持新建、保存、加载日记,并能自动记录指定路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在学习Qt,要求设计一个文本编辑器,实现简单的问价打开、保存和文本编辑的工作,实现完成之后,我看到有自带的calendar Widget,所以顺带实现了点击日历中的日期查看日记和写日记。

发布后的应用程序:
这里写图片描述

总程序:
editorwindow.h

#ifndef EDITORWINDOW_H
#define EDITORWINDOW_H

#include <QMainWindow>
#include <QTextCharFormat>

class QTextEdit;


namespace Ui {
class editorwindow;
}

class editorwindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit editorwindow(QWidget *parent = 0);
    ~editorwindow();

private slots:
    void on_actionNew_triggered();

    void on_actionSave_triggered();

    void on_actionOpen_triggered();

    void on_actionAbout_triggered();

    void on_actionFont_triggered();

    void on_actionLift_triggered();

    void on_actionCenter_triggered();

    void on_actionRight_triggered();

    void on_actionTextBold_triggered();

    void on_actionTextItalic_triggered();

    void on_actionTextUnderLine_triggered();

    void on_actionColor_triggered();

    void on_actionTime_triggered();

    void on_calendarWidget_selectionChanged();

    void on_actionPosition_triggered();

    void on_actionSaveAs_triggered();

private:
    Ui::editorwindow *ui;
    QString curFile;
    bool isSaved;
    void do_file_New();
    void do_file_SaveOrNot();
    void do_file_Save();
    void do_file_SaveAs();
    bool saveFile(const QString& fileName);
    void do_file_open();
    bool do_file_load(const QString& fileName);
    void aboutMyEditor();
    void mergeFormat(QTextCharFormat fmt);
    bool boldcheck;
    bool Italiccheck;
    bool UnderLinecheck;
    QString Position;
};

#endif // EDITORWINDOW_H

editorwindow.cpp:

#include "editorwindow.h"
#include "ui_editorwindow.h"
#include <QtGui>
#include <QMessageBox>
#include <QLineEdit>
#include <QPushButton>
#include <QLabel>
#include <QTextCursor>
#include <QFileDialog>
#include <QFont>
#include <QFontDialog>
#include <QTextEdit>
#include <QTextListFormat>
#include <QTextCharFormat>
#include <QColor>
#include <QColorDialog>
#include <QDateTime>
#include <QDate>

editorwindow::editorwindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::editorwindow)
{
    ui->setupUi(this);
    isSaved = false;//初始化文件为未保存状态
    boldcheck = true;
    Italiccheck = true;
    UnderLinecheck = true;
    curFile = tr("未命名.txt");//初始化文件名为'未命名.txt'

    setWindowTitle(curFile);//初始化主窗口的标题
    //初始化字体和大小
    ui->textEdit->setCurrentFont(QFont("楷体", 15));

    QFile file("D:/Dev/path.txt");
    file.open(QFile::ReadOnly|QFile::Text); //以只读方式打开文件,如果打开失败则返回,弹出对话框
    QTextStream in(&file);//新建流对象,指向选定文件
    Position = in.readAll();//读取路径
}

editorwindow::~editorwindow()
{
    delete ui;
}

//  设置光标的选区,使格式作用于选区内的字符,若没有选区则作用于光标所在处的字符
void editorwindow::mergeFormat(QTextCharFormat fmt)
{
    QTextCursor cursor = ui->textEdit->textCursor();
    if (!cursor.hasSelection()) {
       cursor.select(QTextCursor::WordUnderCursor);
    }
    cursor.mergeCharFormat(fmt);
}

void editorwindow::do_file_New()
{
    do_file_SaveOrNot();
    isSaved = false;
    curFile = tr("未命名.txt");
    setWindowTitle(curFile);
    ui->textEdit->clear();//清除文本编辑器
    ui->textEdit->setVisible(true);//文本编辑器可见
}

void editorwindow::do_file_SaveOrNot()
{
    if(ui->textEdit->document()->isModified())//如果文件被更改过
    {
        QMessageBox box;
        box.setWindowTitle(tr("警告"));
        box.setIcon(QMessageBox::Warning);
        box.setText(curFile+tr("尚未保存,是否保存?"));
        box.setStandardButtons(QMessageBox::Yes|QMessageBox::No);
        if(box.exec()==QMessageBox::Yes)
        do_file_Save();
    }
}

void editorwindow::do_file_Save()
{
//    if(isSaved)//如果文件保存过,直接保存
//    {
//        saveFile(curFile);
//    }
//    else
//    {
//        do_file_SaveAs();//如果文件是第一次保存,调用另存为
//    }
        saveFile(curFile);
}

void editorwindow::do_file_SaveAs()
{
    QString fileName = QFileDialog::getSaveFileName(this,tr("另存为"),curFile);//获取文件名
    if(!fileName.isEmpty())//文件名不为空,则保存文件
    {
        saveFile(fileName);
    }
}

bool editorwindow::saveFile(const QString& fileName)//存储文件
{
    QFile file(fileName);
    if(!file.open(QFile::WriteOnly|QFile::Text))
    //以只写方式打开文件,如果打开失败则返回,弹出对话框
    {
    QMessageBox::warning(this,tr("保存文件"),tr("无法保存文件 %1:\n %2").arg(fileName).arg(file.errorString()));
    return false;//%1和%2表示后面两个arg的值
    }
    QTextStream out(&file);//新建流对象,指向选定文件
    out<<ui->textEdit->toPlainText();//将文本编辑器中的内容以纯文本的形式输出到流对象中
    isSaved = true;
    curFile = QFileInfo(fileName).canonicalFilePath();//获取文件的标准路径
    setWindowTitle(curFile);//将窗口名称改为现在的窗口路径
    return true;
}

void editorwindow::aboutMyEditor()
{
    QMessageBox msgBox;
    msgBox.setText("   这是一个简单日记本桌面应用。                      \n"
                   "   可以从左侧的日历中选取时间以查看当天日记或者新建日记。初次使用请\n"
                   " 在设置选项中设置文件存储路径。祝您使用愉快!\n"
                   "Designed by Huiqiang.All rights reserved! \n"
                   "Nanjing Tech University        ");
    msgBox.exec();
}

void editorwindow::do_file_open()
{
    do_file_SaveOrNot();
    QString fileName = QFileDialog::getOpenFileName(this);
    if(!fileName.isEmpty())
    {
        do_file_load(fileName);
    }
    isSaved = true;
}

bool editorwindow::do_file_load(const QString& fileName)
{
    QFile file(fileName);
    if(!file.open(QFile::ReadOnly|QFile::Text)) //以只读方式打开文件,如果打开失败则返回,弹出对话框
    {
        QMessageBox::warning(this,tr("读取文件"),tr("无法读取文件 %1:\n %2.").arg(fileName).arg(file.errorString()));
        return false;//%1和%2表示后面两个arg的值
    }
    QTextStream in(&file);//新建流对象,指向选定文件
    ui->textEdit->setText(in.readAll());//将文件中所有的内容写到文本编辑器中
    curFile = QFileInfo(fileName).canonicalFilePath();
    setWindowTitle(curFile);
    ui->textEdit->setVisible(true);//将文本设置为可见,此句话必须放在return true前,放在其后就见不到了,因为return语句返回了,此句执行不到
    return true;
}

void editorwindow::on_actionNew_triggered()
{
     do_file_New();
}

void editorwindow::on_actionSave_triggered()
{
    do_file_Save();
}

void editorwindow::on_actionOpen_triggered()
{
    do_file_open();
}

void editorwindow::on_actionAbout_triggered()
{
    aboutMyEditor();
}

void editorwindow::on_actionFont_triggered()
{

    bool ok;
    QFont font = QFontDialog::getFont(&ok, QFont("楷体", 20), this);
    if(ok){
    ui->textEdit->setCurrentFont(font);
    }
}

void editorwindow::on_actionLift_triggered()
{
    ui->textEdit->setAlignment(Qt::AlignLeft);
}

void editorwindow::on_actionCenter_triggered()
{
    ui->textEdit->setAlignment(Qt::AlignCenter);
}

void editorwindow::on_actionRight_triggered()
{
    ui->textEdit->setAlignment(Qt::AlignRight);
}

void editorwindow::on_actionTextBold_triggered()
{
    QTextCharFormat fmt;
    fmt.setFontWeight(boldcheck ? QFont::Bold : QFont::Normal);
    mergeFormat(fmt);
    boldcheck = !boldcheck;
}

void editorwindow::on_actionTextItalic_triggered()
{
    QTextCharFormat fmt;
    fmt.setFontItalic(Italiccheck ? true : false);
    mergeFormat(fmt);
    Italiccheck = !Italiccheck;
}

void editorwindow::on_actionTextUnderLine_triggered()
{
    QTextCharFormat fmt;
    fmt.setFontUnderline(UnderLinecheck ? true : false);
    mergeFormat(fmt);
    UnderLinecheck = !UnderLinecheck;
}

void editorwindow::on_actionColor_triggered()
{
    QColor color = QColorDialog::getColor(Qt::black,this);
    if(color.isValid()){
        QTextCharFormat fmt;
        fmt.setForeground(color);
        mergeFormat(fmt);
    }
}


void editorwindow::on_actionTime_triggered()
{
    QDateTime time = QDateTime::currentDateTime();//获取系统现在的时间
    QString str = time.toString("yyyy-MM-dd     dddd     hh:mm:ss     天气:\n"); //设置显示格式
    ui->textEdit->insertPlainText(str);
    ui->textEdit->insertPlainText("--------------------------------------------------\n");
}



void editorwindow::on_calendarWidget_selectionChanged()
{
    QDate data =  ui->calendarWidget->selectedDate();
    QString datastr = data.toString("yyyy-MM-dd.txt");
    do_file_SaveOrNot();
    QString fileName = Position+"/"+datastr;
    bool result = do_file_load(fileName);
    if(result == false)
    {
        QMessageBox msgBox;
        msgBox.setText("该日没有日记!");
        msgBox.setInformativeText("是否新建日记?");
        msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
        int ret = msgBox.exec();
        if(ret == QMessageBox::Yes){
            do_file_SaveOrNot();
            isSaved = false;
            curFile = fileName;
            setWindowTitle(curFile);
            ui->textEdit->clear();//清除文本编辑器
            ui->textEdit->setVisible(true);//文本编辑器可见
        }
    }
}

void editorwindow::on_actionPosition_triggered()
{
    Position = QFileDialog::getExistingDirectory(this, tr("选择存储路径"),"/home",QFileDialog::ShowDirsOnly
                                                      | QFileDialog::DontResolveSymlinks);
    QFile file("D:/Dev/path.txt");
    file.open(QFile::WriteOnly|QFile::Text);
    QTextStream out(&file);//新建流对象,指向选定文件
    out<<Position;//将路径存储下来
}

void editorwindow::on_actionSaveAs_triggered()
{
    do_file_SaveAs();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值