QT简易记事本

#include "notepad.h"
#include "ui_notepad.h"
#include 
#include 
#include 
#include 
NotePad::NotePad(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::NotePad)
{
    ui->setupUi(this);

    connect(ui->newAction, &QAction::triggered, this, &NotePad::newFileActionSlot );
    connect(ui->openAction, &QAction::triggered, this, &NotePad::openFileActionSlot );
    connect(ui->saveAction, &QAction::triggered, this, &NotePad::saveFileActionSlot );
}

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


void NotePad::newFileActionSlot(){
    ui->textEdit->clear();
    ui->textEdit->setWindowTitle("new file");
}
void NotePad::openFileActionSlot(){
    // QFileDialog::getOpenFileName用于打开一个框,选择文件
    // 返回值是对应的文件名称
    // QCoreApplication::applicationFilePath获取当前应用目录
    QString fileName = QFileDialog::getOpenFileName(this, "打开一个文件 ", QCoreApplication::applicationFilePath(), "*.cpp");
    if (fileName.isEmpty()) {
        QMessageBox::warning(this, "警告 ", "请打开一个文件 ");
    }
    else {
        QFile file(fileName);
        file.open(QIODevice::ReadOnly);
        QByteArray ba = file.readAll();

        ui->textEdit->setText(QString(ba));
        file.close();
    }
}
void NotePad::saveFileActionSlot(){

    QString fileName = QFileDialog::getSaveFileName(this, "保存一个文件 ", QCoreApplication::applicationFilePath());
    if (fileName.isEmpty()) {
        QMessageBox::warning(this, "警告 ", "请保存一个文件 ");
    }
    else {
        // toPlainText获取textEdit中的文本
        QString text = ui->textEdit->toPlainText();
        QFile file(fileName);

        // 文件的读取和写入都是QByteArray对象
        // QByteArray转QString ,QString有对应构造函数
        // QString转QByteArray, QByteArray对象有append方法
        file.open(QIODevice::WriteOnly);
        QByteArray ba;
        ba.append(text);
        file.write(ba) ;
        file.close();
    }
}


void NotePad::keyPressEvent(QKeyEvent* event){
    // 使用快捷键实现文件的保存
    if (event->modifiers() == Qt::ControlModifier && event->key() == Qt::Key_S){
        saveFileActionSlot();
    }
}

void NotePad::mousePressEvent(QMouseEvent* event){
    QPoint pt = event->pos();
    qDebug()<<pt;

    if (event->button() == Qt::LeftButton){
        qDebug()<<"left button";
    }
    else if (event->button() == Qt::RightButton){
        qDebug()<<"right button";
    }
}





你可能感兴趣的:(QT,记事本)