第二章:QT核心机制(二)

作业

1> 将鼠标事件和键盘事件相关代码重新实现一遍

cpp 复制代码
//头文件
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QKeyEvent>        //键盘事件类
#include <QDebug>
#include <QLabel>
#include <QMouseEvent>      //鼠标事件类

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

    //重写键盘按下事件
    void keyPressEvent(QKeyEvent *event) override;
    //重写键盘抬起事件
    void keyReleaseEvent(QKeyEvent *event) override;
    //重写鼠标按下事件
    void mousePressEvent(QMouseEvent *event) override;
    //重写鼠标抬起事件
    void mouseReleaseEvent(QMouseEvent *event) override;
    //重写鼠标双击事件
    void mouseDoubleClickEvent(QMouseEvent *event) override;
    //重写鼠标移动事件
    void mouseMoveEvent(QMouseEvent *event) override;

private:
    Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
cpp 复制代码
//源文件
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //开启鼠标追踪功能
    this->setMouseTracking(true);
}

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

//对键盘按下事件重写
void MainWindow::keyPressEvent(QKeyEvent *event)
{
    qDebug()<<event->text()<<"被按下,对应的键值为:"<<event->key();
    switch(event->key())
    {
        //判断是否为W字符
        case 'W':
        {
            //判断圆球是否脱离了整个界面
            if(ui->label->y() <= -ui->label->height())
            {
                //将租价移动到整个界面的最下方
                ui->label->move(ui->label->x(),this->height());
            }
            //将ui界面上的lab向上偏移
            ui->label->move(ui->label->x(),ui->label->y()-10);
        }
        break;
        //判断是否为S字符
        case 'S':
        {
            //判断圆球是否脱离了整个界面
            if(ui->label->y() >= this->height())
            {
                //将租价移动到整个界面的最上方
                ui->label->move(ui->label->x(),0);
            }
            //将ui界面上的lab向下偏移
            ui->label->move(ui->label->x(),ui->label->y()+10);
        }
        break;
        //判断是否为A字符
        case 'A':
        {
            //判断圆球是否脱离了整个界面
            if(ui->label->x() <= -ui->label->width())
            {
                //将租价移动到整个界面的最右方
                ui->label->move(this->width(),ui->label->y());
            }
            //将ui界面上的lab向左偏移
            ui->label->move(ui->label->x()-10,ui->label->y());
        }
        break;
        //判断是否为D字符
        case 'D':
        {
            //判断圆球是否脱离了整个界面
            if(ui->label->x() >= this->width())
            {
                //将租价移动到整个界面的最左方
                ui->label->move(-ui->label->width(),ui->label->y());
            }
            //将ui界面上的lab向右偏移
            ui->label->move(ui->label->x()+10,ui->label->y());
        }
        break;
    }
}

//对见键盘抬起事件重写
void MainWindow::keyReleaseEvent(QKeyEvent *event)
{
    qDebug()<<event->text()<<"被抬起,对应的键值为:"<<event->key();
}

//对鼠标按下事件重写
void MainWindow::mousePressEvent(QMouseEvent *event)
{
    //判断是哪个键被按下
    if(event->button() == Qt::LeftButton)
    {
        qDebug()<<"鼠标左键被按下,界面下标为:"<<event->pos()<<",全局坐标为:"<<event->globalPos();
    }
    else if(event->button() == Qt::RightButton)
    {
        qDebug()<<"鼠标右键被按下,界面下标为:"<<event->pos()<<",全局坐标为:"<<event->globalPos();
    }
    else if(event->button() == Qt::MiddleButton)
    {
        qDebug()<<"鼠标中键被按下,界面下标为:"<<event->pos()<<",全局坐标为:"<<event->globalPos();
    }
}

//对鼠标抬起事件重写
void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
    //判断是哪个键被抬起
    if(event->button() == Qt::LeftButton)
    {
        qDebug()<<"鼠标左键被抬起,界面下标为:"<<event->pos()<<",全局坐标为:"<<event->globalPos();
    }
    else if(event->button() == Qt::RightButton)
    {
        qDebug()<<"鼠标右键被抬起,界面下标为:"<<event->pos()<<",全局坐标为:"<<event->globalPos();
    }
    else if(event->button() == Qt::MiddleButton)
    {
        qDebug()<<"鼠标中键被抬起,界面下标为:"<<event->pos()<<",全局坐标为:"<<event->globalPos();
    }
}

//对鼠标双击事件重写
void MainWindow::mouseDoubleClickEvent(QMouseEvent *event)
{
    //判断是哪个键被双击
    if(event->button() == Qt::LeftButton)
    {
        qDebug()<<"鼠标左键被双击,界面下标为:"<<event->pos()<<",全局坐标为:"<<event->globalPos();
    }
    else if(event->button() == Qt::RightButton)
    {
        qDebug()<<"鼠标右键被双击,界面下标为:"<<event->pos()<<",全局坐标为:"<<event->globalPos();
    }
    else if(event->button() == Qt::MiddleButton)
    {
        qDebug()<<"鼠标中键被双击,界面下标为:"<<event->pos()<<",全局坐标为:"<<event->globalPos();
    }
}

//对鼠标移动事件重写
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    //判断是哪个键被移动
    if(event->buttons() == Qt::LeftButton)
    {
        qDebug()<<"鼠标左键被移动,界面下标为:"<<event->pos()<<",全局坐标为:"<<event->globalPos();
    }
    else if(event->buttons() == Qt::RightButton)
    {
        qDebug()<<"鼠标右键被移动,界面下标为:"<<event->pos()<<",全局坐标为:"<<event->globalPos();
    }
    else if(event->buttons() == Qt::MiddleButton)
    {
        qDebug()<<"鼠标中键被移动,界面下标为:"<<event->pos()<<",全局坐标为:"<<event->globalPos();
    }

    qDebug()<<"鼠标被移动,界面下标为:"<<event->pos()<<",全局坐标为:"<<event->globalPos();

    ui->label->move(event->x()-ui->label->width()/2,event->y()-ui->label->height()/2);
}
cpp 复制代码
//主函数
#include "mainwindow.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

2> 将文本编辑器功能完善

cpp 复制代码
//头文件
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QFontDialog>      //打开字体对话框
#include <QFont>            //字体类
#include <QMessageBox>      //消息对话框
#include <QColorDialog>     //颜色对话框
#include <QColor>           //颜色类
#include <QFileDialog>      //文件对话框
#include <QDebug>
#include <QFile>            //文件类
#include <QInputDialog>     //输入对话框
#include <QStandardPaths>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void on_fontBtn_clicked();

    void on_colorBtn_clicked();

    void on_openFileBtn_clicked();

    void on_saveBtn_clicked();

    void on_inputBtn_clicked();

private:
    Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
cpp 复制代码
//源文件
#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_fontBtn_clicked()
{
    bool ok;
    //调用字体对话框的静态成员函数,打开字体对话框
    QFont f = QFontDialog::getFont(&ok,                      //接受是否选中字体
                         QFont("楷体",10,10),      //对话框初始字体
                         this,                    //父组件
                         "选择字体");              //对话框标题
    //对是否选中字体进行判断
    if(ok == true)
    {
        //将选中的字体设置到文本编辑器中
        //ui->textEdit->setFont(f);           //对所有编辑器中的字体进行设置
        ui->textEdit->setCurrentFont(f);      //对编辑器中选中的字体进行设置
    }
    else
    {
        QMessageBox::information(this,"提示","用户取消了选择字体");
    }
}

//颜色按钮对应的槽函数
void MainWindow::on_colorBtn_clicked()
{
    //调用静态成员函数,获取系统的颜色对话框
    QColor c = QColorDialog::getColor(QColor("white"),
                                      this,
                                      "选择颜色");
    //对选择的颜色进行判断
    if(c.isValid())
    {
        //表示用户点击的确定按钮
        ui->textEdit->setTextColor(c);              //设置字体颜色
        //ui->textEdit->setTextBackgroundColor(c);  //设置文本背景颜色
    }
    else
    {
        //用户点击的取消按钮
        QMessageBox::information(this,"提示","用户取消了选择颜色");
    }
}

//打开文件按钮对应的槽函数
void MainWindow::on_openFileBtn_clicked()
{
    //调用文件对话框的具体成员函数,打开系统的文件对话框
    QString fname = QFileDialog::getOpenFileName(this,
                                                 "选择文件",
                                                 "./",
                                                 "all(*.*);;text(*.txt);;image(*.png *.jpg *.xpm);;soures(*.cpp)");
    qDebug()<<fname;
    //进行文件io操作
    //1、实例化一个文件对象
    QFile f;                    //使用无参构造
    f.setFileName(fname);       //设置要管理的文件 QFile f(fname);
    //2、打开文件
    if(!f.exists())
    {
        QMessageBox::information(this,"提示","文件不存在!");
        return;
    }
    if(!f.open(QFile::ReadOnly | QFile::WriteOnly))
    {
        QMessageBox::information(this,"提示","文件打开失败!");
    }
    //程序执行至此,表示文件已经打开
    //读取文件中的数据
    QByteArray msg = f.readAll();
    //将读取出来的数据,展示到ui界面文本编辑器中
    ui->textEdit->setText(QString(msg));
    //4、关闭文件
    f.close();
}

//另存为对话框对应的槽函数
void MainWindow::on_saveBtn_clicked()
{
    // 调用文件对话框的具体成员函数,打开系统的文件对话框
    QString fname = QFileDialog::getSaveFileName(this,
                                                 "保存文件",
                                                 "./",
                                                 "文本文件 (*.txt);;所有文件 (*.*);;图片文件 (*.png *.jpg *.xpm);;源代码文件 (*.cpp)");
    // 检查用户是否选择了文件名
    if (fname.isEmpty()) {
        qDebug() << "用户取消了保存操作";
        return;
    }
    qDebug() << "选择的保存文件名: " << fname;
    // 进行文件 I/O 操作
    // 1、实例化一个文件对象
    QFile file(fname);
    // 2、尝试以写入模式打开文件
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::critical(this, "错误", QString("无法打开文件 %1 进行写入: %2").arg(fname).arg(file.errorString()));
        return;
    }
    // 3、创建文本流对象并写入示例文本
    QTextStream out(&file);
    out.setCodec("UTF-8");
    // 读取文本框内的内容并写入文件
    QString content = ui->textEdit->toPlainText();
    out << content;
    // 4、关闭文件
    file.close();
    QMessageBox::information(this, "提示", "文件已成功保存!");
}

//输入对话框对应的槽函数
void MainWindow::on_inputBtn_clicked()
{
    bool ok;            //判断用户是否确定输入
    //调用静态成员函数,获取一个输入对话框
    QString text = QInputDialog::getText(this,      //父组件
                          "输入文本",                   //对话框标题
                          "请输入密码",                //输入框提示文本
                          QLineEdit::Password,            //输入模式
                          "",                 //输入框中的默认文本
                          &ok);                         //判断用户是选中的输入的输入的数据
    //对ok进行判断
    if(ok == true)
    {
        //表示用户确定了输入的数据,可以正常使用数据了
        qDebug()<<text;
    }
    else
    {
        QMessageBox::information(this,"提示","已取消输入");
    }
}
cpp 复制代码
//主函数
#include "mainwindow.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

3> 思维导图
4> 牛客网上 C和C++ 各实现一个 28 的刷题结果

相关推荐
我是小伍同学1 小时前
基于卷积神经网络和Pyqt5的猫狗识别小程序
人工智能·python·神经网络·qt·小程序·cnn
GalenWu4 小时前
对象转换为 JSON 字符串(或反向解析)
前端·javascript·微信小程序·json
GUIQU.4 小时前
【Vue】微前端架构与Vue(qiankun、Micro-App)
前端·vue.js·架构
zxctsclrjjjcph4 小时前
【高并发内存池】从零到一的项目之centralcache整体结构设计及核心实现
开发语言·数据结构·c++·链表
数据潜水员4 小时前
插槽、生命周期
前端·javascript·vue.js
咸鱼2333号程序员4 小时前
Linux ifconfig命令详解
linux·服务器·网络
秦jh_4 小时前
【Linux网络】应用层协议HTTP
linux·运维·服务器·网络·网络协议·tcp/ip·http
2401_837088504 小时前
CSS vertical-align
前端·html
优雅永不过时·4 小时前
实现一个漂亮的Three.js 扫光地面 圆形贴图扫光
前端·javascript·智慧城市·three.js·贴图·shader
炯哈哈5 小时前
【上位机——MFC】单文档和多文档视图架构
开发语言·c++·mfc·上位机