notepad项目实例05:打开历史记录功能(配置文件ui实现)

添加事件action:最近打开

notepad项目实例05:打开历史记录功能(配置文件ui实现)_第1张图片

添加事件”清除打开历史记录“

 notepad项目实例05:打开历史记录功能(配置文件ui实现)_第2张图片

向菜单栏”文件“中添加创建好的事件,”清除打开历史记录“添加到”最近打开“选项下作为子选项,

添加的方式为拖拽,子选项拖拽到”最近打开“的”+“号上停一下然后放置在”在这里输入“这个位置即可。

添加执行函数

notepad项目实例05:打开历史记录功能(配置文件ui实现)_第3张图片

编写代码实现功能:

1.保存打开记录

2.读取打开记录

3.把读取记录变成菜单显示出来

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += c++11
qtHaveModule(printsupport): QT+=printsupport #支持打印

# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
    main.cpp \
    mainwindow.cpp

HEADERS += \
    mainwindow.h

FORMS += \
    mainwindow.ui

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

RESOURCES += \
    images.qrc

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include 
#include 
#include 

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void on_new_file_triggered();
    void on_open_file_triggered();
    void on_save_file_triggered();
    void on_save_as_triggered();
    void on_paste_triggered();
    void on_cut_triggered();
    void on_copy_triggered();
    void on_font_triggered();
    void on_info_triggered();
    void on_undo_triggered();
    void on_redo_triggered();
    void on_exit_triggered();
    void on_print_triggered();
    void on_bolder_triggered(bool checked);
    void on_italics_triggered(bool checked);
    void on_underline_triggered(bool checked);

    void on_clear_history_triggered();

private:
    Ui::MainWindow *ui;
    QString currentFile; // 当前文件
    void initMenu();
    void on_open_recent_file();
};
#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include 
#include 
#include 
#include 
#include 
#include  // 保存配置文件

// 保存打开历史记录
void saveHistory(QString path);
// 获取历史记录
QList getHistory();

// 先判断是否支持打印


// 定义全局变量
QSettings *mSettings;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setCentralWidget(ui->textEdit);
    // 初始化保存历史记录的全局变量
    if (mSettings == NULL) {
        mSettings = new QSettings("settings.ini", QSettings::IniFormat);
    }
    initMenu();
}

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


void MainWindow::initMenu()
{
    // 获取menu
    // 用于查找MainWindow中名为"recent"的子窗口,并将其存储为指向 `QMenu` 类型对象的指针 `recent`。
    QMenu *recent = this->findChild("recent");
    // qDebug() << recent->title() << endl;
    qDebug() << "最近打开" << endl;
    // 获取Action
    QSet chList = recent->children().toSet();
    foreach(QObject *ch, chList) {
        QAction *action = (QAction *)ch;
        // 清空子菜单栏action
        recent->removeAction(action);
    }
    QList lists = getHistory();

    // 打开历史记录按时间从近到远
    for (int i = lists.size() - 1; i >= 0; --i) {
        // 生成子菜单
        recent->addAction(lists[i], this, &MainWindow::on_open_recent_file);
    }
    // 添加"清除历史记录"action
    if (lists.size() > 0) {
        recent->addAction("清楚历史菜单", this, &MainWindow::on_clear_history_triggered, QKeySequence("Ctrl+Alt+Shift+C"));
    }
}

// 获取历史记录
QList getHistory()
{
    // 打开开始读入
    int size = mSettings->beginReadArray("history");
    // 创建返回对象
    QList lists;
    for (int i = 0; i < size; i++) {
        mSettings->setArrayIndex(i);
        QString path = mSettings->value("path").toString();
        lists.append(path);
        qDebug() << i << ":" << path;
    }
    // 关闭开始读入
    mSettings->endArray();
    return lists;
}

// 保存打开历史记录
void saveHistory(QString path)
{
    // 获取历史
    QList lists = getHistory();
    lists.append(path);
    foreach(QString str, lists) {
        if (str == path) {
            lists.removeOne(str);
        }
    }
    lists.append(path);
    // lists.toSet().toList(); // 去重
    // 打开开始写入
    mSettings->beginWriteArray("history");
    for (int i = 0; i < lists.size(); ++i) {
        mSettings->setArrayIndex(i);
        // 保存字符串
        mSettings->setValue("path", lists[i]);
    }
    // 关闭开始写入
    mSettings->endArray();
}

// 新建文件
void MainWindow::on_new_file_triggered()
{
    qDebug() << "start create new file ..." << endl;
    currentFile.clear(); // 如果之前有文件的话先进性清空
    ui->textEdit->setText(""); // 清空文件内容
}

void MainWindow::on_open_recent_file()
{
    QAction *action = (QAction*)sender();
    QString filename = action->text();
    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QMessageBox::warning(this, "警告", "无法打开此文件"+file.errorString());
    }
    currentFile = filename;
    setWindowTitle(filename);
    QTextStream in(&file);
    QString text = in.readAll();
    ui->textEdit->setText(text);
    file.close();
    saveHistory(currentFile);
    initMenu();
}

// 打开文件
void MainWindow::on_open_file_triggered()
{
    QString filename = QFileDialog::getOpenFileName(this, "打开文件");
    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly | QFile::Text)) {
        QMessageBox::warning(this, "警告", "无法打开此文件 : " + file.errorString());
        return;
    }
    currentFile = filename;
    setWindowTitle(filename);
    QTextStream in(&file);
    QString text = in.readAll();
    ui->textEdit->setText(text);
    file.close();
    saveHistory(currentFile);
    initMenu();
}

// 保存文件
void MainWindow::on_save_file_triggered()
{
    QString filename;
    if (currentFile.isEmpty()) {
        filename = QFileDialog::getSaveFileName(this, "保存文件");
        currentFile = filename;
    } else {
        filename = currentFile;
    }
    QFile file(filename);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::warning(this, "警告", "无法保存文件:"+file.errorString());
        return;
    }
    setWindowTitle(filename);
    QTextStream out(&file);
    QString text = ui->textEdit->toPlainText();
    out << text;
    file.close();
    saveHistory(currentFile);
    initMenu();
}

// 另存为
void MainWindow::on_save_as_triggered()
{
    QString filename;
    filename = QFileDialog::getSaveFileName(this, "另存为");
    QFile file(filename);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::warning(this, "警告", "无法保存文件:"+file.errorString());
        return;
    }
    setWindowTitle(filename);
    QTextStream out(&file);
    QString text = ui->textEdit->toPlainText();
    out << text;
    file.close();
    saveHistory(currentFile);
    initMenu();
}

// 复制
void MainWindow::on_copy_triggered()
{
    ui->textEdit->copy();
}

// 粘贴
void MainWindow::on_paste_triggered()
{
    ui->textEdit->paste();
}

// 剪切
void MainWindow::on_cut_triggered()
{
    ui->textEdit->cut();
}

// 字体
void MainWindow::on_font_triggered()
{
    bool fontSelected;
    QFont font = QFontDialog::getFont(&fontSelected, this);
    if (fontSelected) {
        ui->textEdit->setFont(font);
    }
}

// 撤销
void MainWindow::on_undo_triggered()
{
    ui->textEdit->undo();
}

// 取消撤销
void MainWindow::on_redo_triggered()
{
    ui->textEdit->redo();
}

// 退出
void MainWindow::on_exit_triggered()
{
    QCoreApplication::exit();
}

// 信息
void MainWindow::on_info_triggered()
{
    QMessageBox::about(this, "这是我的notepad", "欢迎学习和使用");
}

// 打印
void MainWindow::on_print_triggered()
{

}

// 加粗
void MainWindow::on_bolder_triggered(bool checked)
{
    qDebug() << "on_bolder_triggered" << endl;
    ui->textEdit->setFontWeight(checked);
}

// 斜体
void MainWindow::on_italics_triggered(bool checked)
{
    ui->textEdit->setFontItalic(checked);
}

// 下划线
void MainWindow::on_underline_triggered(bool checked)
{
    ui->textEdit->setFontUnderline(checked);
}

// 清除历史记录
void MainWindow::on_clear_history_triggered()
{
    qDebug() << "on_clear_history_triggered..." << endl;
    mSettings->remove("history");
    initMenu();
}
#include "mainwindow.h"

#include 
#include "treewidget.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

你可能感兴趣的:(qt学习笔记,qt)