mainwindow.h
核心函数
- QFileDialog::getOpenFileName()
- QFileDialog::getSaveFileName()
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include<QFileDialog>
#include<QMessageBox>
#include<QDebug>
#include<QFile>
#include<QKeyEvent>
#include<QMouseEvent>
QT_BEGIN_NAMESPACE
namespace Ui {
class MainWindow;
}
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
void keyPressEvent(QKeyEvent *k);
void mousePressEvent(QMouseEvent *m);
~MainWindow();
private:
Ui::MainWindow *ui;
private slots:
void newActionSlot();
void openActionSlot();
void saveActionSlot();
};
#endif
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->setWindowTitle("记事本");
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{
QFile file(filename);
file.open(QIODevice::ReadOnly);
QByteArray ba = file.readAll();
file.close();
ui->textEdit->setText(QString(ba));
}
}
void MainWindow::saveActionSlot()
{
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)
{
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()<<"右键被按下";
}