请选择 进入手机版 | 继续访问电脑版
MSIPO技术圈 首页 IT技术 查看内容

QT创建文本编辑窗口

2023-07-13

#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

 

#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,"错误","没有选择字体");
    }
}

相关阅读

热门文章

    手机版|MSIPO技术圈 皖ICP备19022944号-2

    Copyright © 2024, msipo.com

    返回顶部