Qt day3

完善文本编辑器
mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QWidget>

namespace Ui {
class MainWindow;
}

class MainWindow : public QWidget
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
public slots:
    void mainWindow_slot();
private slots:
    void on_btnFont_clicked();

    void on_btnColor_clicked();

    void on_btnOpen_clicked();

    void on_btnSave_clicked();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

mainWindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFontDialog>
#include <QMessageBox>
#include <QColorDialog>
#include <QFileDialog>
MainWindow::MainWindow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::mainWindow_slot()
{
    show();
}

void MainWindow::on_btnFont_clicked()
{
    bool ok;
    QFont font = QFontDialog::getFont(&ok,QFont("宋体",12,2,false),this,"字体");
    if(ok) {
        this->ui->textEdit->setCurrentFont(font);
    } else {
        QMessageBox messageBox(QMessageBox::Information,"提示","用户没有选择字体",QMessageBox::Ok);
        messageBox.exec();
    }
}

void MainWindow::on_btnColor_clicked()
{
    QColor color = QColorDialog::getColor(QColor(100,100,100),this,"颜色");
    if(color.isValid()) {
        this->ui->textEdit->setTextColor(color);
    } else {
        QMessageBox::information(this,"提示","用户没有选择颜色");
    }

}

void MainWindow::on_btnOpen_clicked()
{
   QString path= QFileDialog::getOpenFileName(this,"打开文件","./","文件(*.txt);;图片(*.png *.jpg *.bmp);;所有文件(*.*)");
   QFile file(path);
   if(!file.exists()) {
       QMessageBox::information(this,"提示","打开的文件不存在");
       return;
   }
   if(!file.open(QIODevice::ReadWrite)) {
       QMessageBox::information(this,"提示","打开文件失败");
       return;
   }
   QByteArray byteArr = file.readAll();

   file.close();
   ui->textEdit->setText(byteArr);
}

void MainWindow::on_btnSave_clicked()
{
    QString path = QFileDialog::getSaveFileName(this,"保存","./","文件(*.txt);;图片(*.png *.jpg *.bmp);;所有文件(*.*)");
    QFile file(path);

    if(!file.open(QIODevice::Append)) {
        QMessageBox::information(this,"提示","保存文件失败");
        return;
    }
    QString text = ui->textEdit->toPlainText();
    text.data();
    int len = file.write(text.toLocal8Bit());
    if(len>0) {
        QMessageBox::information(this,"提示","保存文件成功");
    }
    file.close();

}

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值