1.文本框的实现
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
//主窗口
this->setFixedSize(600,400);
this->setWindowTitle("文本界面");
//文本框
text = new QTextEdit(this);
text->setFixedSize(400,300);
text->move(100,20);
//按钮
fontbtn=new QPushButton(this);
fontbtn->setText("字体");
fontbtn->move(100,330);
colorbtn=new QPushButton(this);
colorbtn->setText("颜色");
colorbtn->move(200,330);
openbtn=new QPushButton(this);
openbtn->setText("打开文件");
openbtn->move(300,330);
savebtn=new QPushButton(this);
savebtn->setText("保存文件");
savebtn->move(400,330);
connect(this->fontbtn,&QPushButton::clicked,this,&MainWindow::fontbtn_slot);
connect(this->colorbtn,&QPushButton::clicked,this,&MainWindow::colorbtn_slot);
connect(this->openbtn,&QPushButton::clicked,this,&MainWindow::openbtn_slot);
connect(this->savebtn,&QPushButton::clicked,this,&MainWindow::savebtn_slot);
}
//font
void MainWindow::fontbtn_slot()
{
bool ok;
QFont font = QFontDialog::getFont(&ok,
QFont("宋体",10),
this);
if(ok)
{
qDebug() << "font has setted";
this->text->setFont(font);
}
else {
qDebug() << "font does not have setted";
}
}
void MainWindow::colorbtn_slot()
{
QColor color = QColorDialog::getColor(Qt::black,
this,
"选择颜色");
if(color.isValid())
{
qDebug() << "color has setted";
this->text->setTextColor(color);
}
else {
qDebug() << "color does not have setted";
}
}
//open
void MainWindow::openbtn_slot()
{
QString filename = QFileDialog::getOpenFileName(this,
tr("打开文件"),
"./",
tr("ALL(*.*)"));
if(filename.isEmpty())
{
qDebug() << "打开失败";
}
qDebug() <<filename;
QFile file(filename);//实例化对象
if(!file.exists())//判断对象是否存在
{
qDebug() << "你要打开的文件不存在";
return;
}
//被打开对象具有读写权限
else if(!file.open(QIODevice::ReadWrite))
{
qDebug() << "打开失败";
return;
}
//读文件中所有数据
QByteArray text = file.readAll();
//读取的数据写入text
this->text->setText(QString::fromLocal8Bit(text));
file.close();
}
void MainWindow::savebtn_slot()
{
QString filename = QFileDialog::getSaveFileName(this,
tr("保存文件"),
"./",
tr("ALL(*.*)"));
QFile file(filename);
if(!file.open(QIODevice::ReadWrite))
{
qDebug() << "打开失败" ;
return;
}
QString msg = this->text->toPlainText();
file.write(msg.toLocal8Bit());
file.close();
}
MainWindow::~MainWindow()
{
delete ui;
}