文章来源:https://www.toymoban.com/news/detail-560924.html
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QFont>
#include <QFontDialog>
#include <QMessageBox>
#include <QColor>
#include <QColorDialog>
#include <QFileDialog>
#include <QDebug>
#include <QFile>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_colorbtn_clicked();
void on_openbtn_clicked();
void on_savebtn_clicked();
void on_txtbtn_clicked();
private:
Ui::MainWindow *ui;
QString filename;
};
#endif // MAINWINDOW_H
文章来源地址https://www.toymoban.com/news/detail-560924.html
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_colorbtn_clicked()
{
QColor c = QColorDialog::getColor(QColor(0,255,0),this,"选择颜色");
if(c.isValid()){
ui->textEdit->setTextColor(c);
}else {
QMessageBox::information(this,"错误","没有选择颜色");
}
}
void MainWindow::on_openbtn_clicked()
{
filename=QFileDialog::getOpenFileName(this,"打开文件","./","text file(*.txt)");
qDebug()<<filename;
QFile file(filename);
if(!file.exists()) {
QMessageBox::information(this,"错误","文件不存在");
}
if(!file.open(QIODevice::ReadWrite)){
QMessageBox::information(this,"错误","文件打开失败");
return;
}
QByteArray msg=file.readAll();
file.close();
ui->textEdit->setText(QString::fromUtf8(msg));
}
void MainWindow::on_savebtn_clicked()
{
QString pathName = QFileDialog::getSaveFileName(this, "保存文件", "./", "TEXT(*.txt)");
//实例化文件对象
QFile file(pathName);
//打开文件
file.open(QIODevice::WriteOnly | QIODevice::Truncate);
//写入数据
QString text = ui->textEdit->toPlainText();
file.write(text.toLocal8Bit());
//关闭文件
file.close();
}
void MainWindow::on_txtbtn_clicked()
{
bool ok;
QFont f = QFontDialog::getFont(&ok,QFont("宋体",10,2,false),this,"选择字体");
if(ok){
ui->textEdit->setCurrentFont(f);
}
else{
QMessageBox::information(this,"错误","没有选择字体");
}
}
到了这里,关于QT创建文本编辑窗口的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!