试着学了一下qt,拿个小记事本练练手
(工具: Win10 Qt 5.14.2 Qt Creator 4.12.2)
思路:实现记事本基本功能,新建文件、打开文件、可在文本框内更改文件、保存(另存为)文件、关闭文件、在标题栏显示打开文件路径.
页面布局:
widget.h:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void on_save_clicked();
void on_open_clicked();
void on_new_2_clicked();
void on_clear_clicked();
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
main.cpp:
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
w.setWindowTitle("notepad");
return a.exec();
}
widget.cpp:(核心)
#include "widget.h"
#include "ui_widget.h"
#include <QFile>
#include <QFileDialog>
#include <QDebug>
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_save_clicked()
{
QString filename = QFileDialog::getSaveFileName(this,tr("save"),"untitled.txt",tr("All File(*.*)"));//保存文件对话框
QFile file(filename);//创建文件对象
file.open(QIODevice::WriteOnly|QIODevice::Text);//只写方式打开文件
QTextStream out(&file);//(将out与文件关联)
out.setCodec("utf-8");//设置文件编码'utf-8'
QString context = ui->text->toPlainText();//读取文本框内容
out<<context;//写入文件
file.close();
}
void Widget::on_open_clicked()
{
QString filename = QFileDialog::getOpenFileName(this,tr("open"),"c:/",tr("All File(*.*)"));//打开文件对话框
QFile file(filename);//创建文件对象
file.open(QIODevice::ReadOnly|QIODevice::Text);//以只读模式打开文件
QTextStream in(&file);
in.setCodec("utf-8");//用QTextStream设置文件编码
while(!in.atEnd()){
QString context = in.readLine();//逐行读取文件
ui->text->append(context);//将读取内容追加到文本框
}
file.close();
this->setWindowTitle("notepad "+filename);
}
void Widget::on_new_2_clicked()
{
QString filename = QFileDialog::getSaveFileName(this,tr("new"),"untitled.txt",tr("Text(*.txt)"));//新建文件对话框
QFile file(filename);//创建文件对象
file.open(QIODevice::WriteOnly|QIODevice::Text);//创建新文件(以只写方式打开,若无当前文件,则新建一个空文件)
file.close();
}
void Widget::on_clear_clicked()
{
ui->text->clear();//清除文本框内容
this->setWindowTitle("notepad");
}
做得很简单..运行了一下还挺好用.
打包运行:
1:将Creator左下角构建改为Release:
2: 运行后来到项目文件路径,把单个exe文件放到单独一个文件夹(防止打包失败)
3:找到qt对应环境,用自带工具windeployqt打包
ok了