qfedu-qt-level/homework-day2-2/mainwindow.cpp

98 lines
3.2 KiB
C++
Raw Permalink Normal View History

2023-08-08 22:36:21 +08:00
#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
2023-08-08 22:37:07 +08:00
setWindowTitle("简单记事");
setFixedSize(800,600);
QPixmap window_icon;
window_icon.load(":logo");
setWindowIcon(QIcon(window_icon));
menu_bar = new QMenuBar(this); // 父组件为当前 MainWindow
setMenuBar(menu_bar);
menu1 = new QMenu("文件",menu_bar); // 父组件为 menu_bar
openAction = new QAction("打开",menu1); // 父组件为 menu1
saveAction = new QAction("保存",menu1);
exitAction = new QAction("退出",menu1);
openAction->setShortcut(QKeySequence(tr("ctrl+o"))); // 快捷键绑定
saveAction->setShortcut(QKeySequence(Qt::CTRL+Qt::Key_S));
exitAction->setShortcut(QKeySequence(tr("ctrl+q")));
connect(openAction,&QAction::triggered,[&]{ // 事件绑定
qDebug()<<"打开...";
// 打开文件
QString file_path = QFileDialog::getOpenFileName(this,"打开文件",".","Text(*.txt);;Markdown(*.md)");
QFile file(file_path);
if(!file.open(QIODevice::ReadOnly|QIODevice::Text)){
QMessageBox::critical(this,"错误","文件路径 "+file_path+" 打开错误");
return; // 提前返回
}
QTextStream in(&file);
text_edit->setMarkdown(in.readAll());
file.close();
});
connect(saveAction,&QAction::triggered,[&]{
qDebug()<<"保存...";
QString file_path = QFileDialog::getSaveFileName(this,"保存文件",".","Markdown(*.md)");
QFile file(file_path);
if(!file.open(QIODevice::WriteOnly|QIODevice::Text)){
QMessageBox::critical(this,"错误","文件路径 "+file_path+"无法保存");
return;
}
QTextStream out(&file);
out << text_edit->toMarkdown();
file.close();
});
connect(exitAction,&QAction::triggered,[&]{
qDebug()<<"退出...";
this->close();
});
openAction->setIcon(QIcon(":open"));
saveAction->setIcon(QIcon(":save"));
menu1->addAction(openAction);
menu1->addAction(saveAction);
menu1->addAction(exitAction);
menu2 = new QMenu("编辑",menu_bar);
menu3 = new QMenu("查看",menu_bar);
menu4 = new QMenu("关于",menu_bar);
aboutAction = new QAction("关于软件",menu4);
aboutQtAction = new QAction("关于Qt",menu4);
connect(aboutAction,&QAction::triggered,[&]{
QMessageBox::about(this,"简单记事","这是一个简单的记事本");
});
connect(aboutQtAction,&QAction::triggered,[&]{
QMessageBox::aboutQt(this);
});
menu4->addAction(aboutAction);
menu4->addAction(aboutQtAction);
menu_bar->addMenu(menu1);
menu_bar->addMenu(menu2);
menu_bar->addMenu(menu3);
menu_bar->addMenu(menu4);
status_bar = new QStatusBar(this);
QLabel *left_status_label = new QLabel("行4 列19",status_bar);
QLabel *right_status_label = new QLabel("utf-8",status_bar);
status_bar->addWidget(left_status_label);
status_bar->addPermanentWidget(right_status_label); // 添加永久小部件
setStatusBar(status_bar);
text_edit = new QTextEdit("文本区占位符",this);
setCentralWidget(text_edit);
2023-08-08 22:36:21 +08:00
}
MainWindow::~MainWindow()
{
}