73 lines
2.6 KiB
C++
73 lines
2.6 KiB
C++
|
#include "mainwindow3.h"
|
||
|
|
||
|
MainWindow3::MainWindow3(QWidget *parent) : QMainWindow(parent)
|
||
|
{
|
||
|
setWindowTitle("对话框学习中...");
|
||
|
setWindowIcon(QIcon(":/icon/start"));
|
||
|
resize(1200, 960);
|
||
|
|
||
|
mEdit = new QTextEdit(this);
|
||
|
//mEdit->close();
|
||
|
setCentralWidget(mEdit);
|
||
|
|
||
|
|
||
|
QStatusBar *bar = new QStatusBar(this);
|
||
|
btn1 = new QPushButton("打开文本文件", bar);
|
||
|
btn2 = new QPushButton("保存文本文件", bar);
|
||
|
btn3 = new QPushButton("颜色对话框", bar);
|
||
|
btn4 = new QPushButton("字体对话框", bar);
|
||
|
bar->addWidget(btn1);
|
||
|
bar->addWidget(btn2);
|
||
|
bar->addWidget(btn3);
|
||
|
bar->addWidget(btn4);
|
||
|
|
||
|
connect(btn1, &QPushButton::clicked, [&](){
|
||
|
// 获取待打开的文件名 (已存在的文件)
|
||
|
// QString fileName = QFileDialog::getOpenFileName(this, "选择图片文件", ".", "Png(*.png);;Jpeg(*.jpg)");
|
||
|
QString fileName = QFileDialog::getOpenFileName(this, "选择文本文件", ".", "Text(*.txt)");
|
||
|
qDebug() << "打开文件的位置:" << fileName ;
|
||
|
QFile file(fileName);
|
||
|
if(!file.open(QIODevice::ReadOnly|QIODevice::Text)){
|
||
|
// 以只读文本的模式打开文件失败
|
||
|
QMessageBox::critical(this, "错误", fileName+" 打开失败!");
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
QTextStream in(&file);
|
||
|
mEdit->setText(in.readAll());
|
||
|
file.close();
|
||
|
});
|
||
|
|
||
|
connect(btn2, &QPushButton::clicked, [&](){
|
||
|
// 保存文件时,获取待保存的文件名 (可以是新文件)
|
||
|
// QString fileName = QFileDialog::getSaveFileName(this,"保存文件位置",".");
|
||
|
QString fileName = QFileDialog::getSaveFileName(this,"保存文件位置","d:/", "Text(*.txt)");
|
||
|
qDebug() << "保存文件的位置: " << fileName ;
|
||
|
QFile file(fileName);
|
||
|
if(!file.open(QIODevice::WriteOnly|QIODevice::Text)){
|
||
|
QMessageBox::critical(this, "错误", fileName+" 保存失败!");
|
||
|
return;
|
||
|
}
|
||
|
QTextStream out(&file);
|
||
|
// 将文本编辑控件 mEdit 中的文本写入到文件中。
|
||
|
out << mEdit->toPlainText(); // 调用 mEdit->toPlainText() 将返回编辑控件中的纯文本内容
|
||
|
file.close();
|
||
|
});
|
||
|
|
||
|
connect(btn3, &QPushButton::clicked, [&](){
|
||
|
QColor color = QColorDialog::getColor(Qt::black,this,"字体颜色选择");
|
||
|
|
||
|
mEdit->setTextBackgroundColor(color);
|
||
|
// mEdit->setTextColor(color); // 条件: 光标选中的文本来设置颜色
|
||
|
});
|
||
|
|
||
|
connect(btn4, &QPushButton::clicked, [&](){
|
||
|
bool yes = true;
|
||
|
QFont font = QFontDialog::getFont(&yes,this);
|
||
|
mEdit->setCurrentFont(font);
|
||
|
|
||
|
});
|
||
|
|
||
|
setStatusBar(bar);
|
||
|
}
|