QT文件操作【记事本】
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->setWindowTitle("记事本");
//连接函数,谁发出信息,发出什么信号,谁接收信号,执行什么操作
//自定义三个槽函数,newActionSlot,openActionSlot,saveActionSlot
connect(ui->newAction,&QAction::triggered,this,&MainWindow::newActionSlot);
connect(ui->openAction,&QAction::triggered,this,&MainWindow::openActionSlot);
connect(ui->saveAction,&QAction::triggered,this,&MainWindow::saveActionSlot);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::newActionSlot()
{
//清空内容
ui->textEdit->clear();
this->setWindowTitle("新建文本文档.txt");
}
void MainWindow::openActionSlot()
{
//打开文件资源管理窗口,获取选定的文件的路径
QString filename= QFileDialog::getOpenFileName(this, "打开文件",
QCoreApplication::applicationFilePath(), "*.cpp");
if(filename.isEmpty())
{
QMessageBox::warning(this,"警告","请打开一个文件!");
}
else{
//qDebug() << filename;
//通过文件路径,构建文件对象
QFile file(filename);
//只读方式打开
file.open(QIODevice::ReadOnly);
//读取文件中的所有内容到字节数组中
QByteArray ba = file.readAll();
//关闭文件对象
file.close();
//将读取的数据存储到textEdit中
ui->textEdit->setText(QString(ba));
}
}
void MainWindow::saveActionSlot()
{
//弹出文件资源管理器窗口,选择文件夹。
//QCoreApplication::applicationFilePath()表示当前根目录
QString filename=QFileDialog::getSaveFileName(this,"保存文件",
QCoreApplication::applicationFilePath());
if(filename.isEmpty())
QMessageBox::warning(this,"警告","请选择一个文件!");
else
{
QFile file(filename);
file.open(QIODevice::WriteOnly);
QByteArray ba;
ba.append(ui->textEdit->toPlainText().toUtf8());
file.write(ba);
file.close();
QMessageBox::about(this,"提示","保存成功");
}
}
void MainWindow::keyPressEvent(QKeyEvent *k)
{
//键盘按下事件,一个父类的虚函数,能够检测键盘事件。Ctrl+S调用保存函数
if(k->modifiers()==Qt::ControlModifier&&k->key()==Qt::Key_S)
saveActionSlot();
}
void MainWindow::mousePressEvent(QMouseEvent *m)
{
QPoint pt = m->pos();
qDebug()<<pt;
if(m->button()==Qt::LeftButton)
qDebug()<<"左键被按下";
else if(m->button()==Qt::RightButton)
qDebug()<<"右键被按下";
}