单例模式(下)

news/2024/7/7 18:41:56 标签: qt, 单例模式

文章目录

  • 文章介绍
  • 步骤安排及单例讲解
  • step1:注册单例类型(main.cpp)
  • step2:定义类和私有构造函数(keyboardinputmanager.h)
  • step3:(keyboardinputmanager.cpp)
  • step4:在qml中调用keyboardinputmanager类(main.qml)
  • 重点步骤
    • main.cpp
    • keyboardinputmanager.h
    • keyboardinputmanager.cpp
    • main.qml

文章介绍

给一个单例模式的例子,实现将键盘输入数据打印到界面文本框的操作

步骤安排及单例讲解

step1:注册单例类型(main.cpp)
step2:定义类和私有构造函数(keyboardinputmanager.h)
step3:(keyboardinputmanager.cpp)
step4:在qml中调用keyboardinputmanager类(main.qml)
单例模式的优点:非常适合在 QML 中集成复杂的后端逻辑,使得前端界面可以直接调用后端逻辑的单例实例进行数据处理或业务逻辑运算。

step1:注册单例类型(main.cpp)

main.cpp中只用关注 qmlRegisterSingletonInstance("com.example", 1, 0, "KeyboardInputManager", KeyboardInputManager::instance());;
这行代码将 KeyboardInputManager注册为 QML 中的单例类型

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "KeyboardInputManager.h"

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    qmlRegisterSingletonInstance("com.example", 1, 0, "KeyboardInputManager", KeyboardInputManager::instance());

    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

step2:定义类和私有构造函数(keyboardinputmanager.h)

#ifndef KEYBOARDINPUTMANAGER_H
#define KEYBOARDINPUTMANAGER_H

#include <QObject>

// KeyboardInputManager 类:管理键盘输入的单例类
class KeyboardInputManager : public QObject
{
    Q_OBJECT
public:
    // 获取单例实例的方法
    static KeyboardInputManager* instance()
    {
        // 静态局部变量,确保单例
        static KeyboardInputManager instance;
        return &instance;
    }

signals:
    // 按键事件信号,传递按键文本
    void keyPressed(const QString &key);

protected:
    // 事件过滤器方法,用于捕获和处理键盘事件
    bool eventFilter(QObject *obj, QEvent *event) override;

private:
    // 私有构造函数,确保单例模式
    KeyboardInputManager();
    // 私有析构函数
    ~KeyboardInputManager();
    // 禁用拷贝构造函数
    KeyboardInputManager(const KeyboardInputManager&) = delete;
    // 禁用赋值运算符
    KeyboardInputManager& operator=(const KeyboardInputManager&) = delete;
};

#endif // KEYBOARDINPUTMANAGER_H



step3:(keyboardinputmanager.cpp)

#include "KeyboardInputManager.h"
#include <QGuiApplication>
#include <QKeyEvent>

// 构造函数:安装事件过滤器以捕获键盘事件
KeyboardInputManager::KeyboardInputManager()
{
    // 安装事件过滤器,将当前实例作为事件过滤器
    QGuiApplication::instance()->installEventFilter(this);
}

// 析构函数:默认析构函数
KeyboardInputManager::~KeyboardInputManager() {}

// 事件过滤器:捕获并处理键盘事件
bool KeyboardInputManager::eventFilter(QObject *obj, QEvent *event)
{
    // 检查事件类型是否为键盘按下事件
    if (event->type() == QEvent::KeyPress) {
        // 将事件转换为键盘事件
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
        // 发射 keyPressed 信号,将按键文本传递给连接的槽函数
        emit keyPressed(keyEvent->text());
        // 返回 true 表示事件已处理
        return true;
    } else {
        // 调用父类的事件过滤器处理其他类型的事件
        return QObject::eventFilter(obj, event);
    }
}


step4:在qml中调用keyboardinputmanager类(main.qml)

import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Window 2.15
import com.example 1.0

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Keyboard Input")

    TextArea {
        id: textArea
        anchors.fill: parent
        wrapMode: Text.Wrap
        focus: true
        Keys.onPressed: {
            KeyboardInputManager.keyPressed(event.text)
        }
    }

    Connections {
        target: KeyboardInputManager

        onKeyPressed: {
            textArea.text += key
        }
    }
}

重点步骤

main.cpp

在这里插入图片描述

keyboardinputmanager.h

在这里插入图片描述

keyboardinputmanager.cpp

在这里插入图片描述

main.qml

在这里插入图片描述


http://www.niftyadmin.cn/n/5534859.html

相关文章

Neo4j 图数据库 高级操作

Neo4j 图数据库 高级操作 文章目录 Neo4j 图数据库 高级操作1 批量添加节点、关系1.1 直接使用 UNWIND 批量创建关系1.2 使用 CSV 文件批量创建关系1.3 选择方法 2 索引2.1 创建单一属性索引2.2 创建组合属性索引2.3 创建全文索引2.4 列出所有索引2.5 删除索引2.6 注意事项 3 清…

基于weixin小程序农场驿站系统的设计

管理员账户功能包括&#xff1a;系统首页&#xff0c;个人中心&#xff0c;农场资讯管理&#xff0c;用户管理&#xff0c;卖家管理&#xff0c;用户分享管理&#xff0c;分享类型管理&#xff0c;商品信息管理&#xff0c;商品类型管理 开发系统&#xff1a;Windows 架构模式…

RClone挂载有阿里云的AList

转自个人博客&#xff1a;https://www.jjy2023.cn/2024/05/23/rclone%e6%8c%82%e8%bd%bd%e6%9c%89%e9%98%bf%e9%87%8c%e4%ba%91%e7%9a%84alist-md/ RClone挂载一般的AList可以直接使用mount命令&#xff0c;但是阿里云需要使用指定头部Referer:https://www.aliyundrive.com/ &a…

QListView自定义item(结合QSqlQueryModel)

QListView:绘制自定义List&#xff08;一&#xff09;——设置ItemDelegate_qt_繁星执着-开放原子开发者工作坊 (csdn.net) QListView自定义Item_qlistview 自定义item-CSDN博客 结合我写的上一篇文章&#xff1a; QTableView与QSqlQueryModel的简单使用-CSDN博客 这次尝试…

OpenCV——实现裁剪YOLO格式的图片目标并按图片名保存

import os import cv2def crop_image(image_path, label_path, output_folder):# 读取图片img cv2.imread(image_path)height, width, _ img.shape# 读取标签文件with open(label_path, r) as file:labels file.readlines()img_id 1# 遍历每个标签for label in labels:part…

Matplotlib 线条的样式

标记型 特点 描述 . 点标记 , 像素标记 o 圆圈标记 v triangle_down 标记 ^ triangle_up 标记 < triangle_left 标记 > triangle_right 标记 1 tri_down 标记 2 tri_up 标记 3 三左标记 4 tri_right 标记 8 八角形标记 s 方形标记 p 五边形…

word 转pdf 中图片不被压缩的方法

word 转pdf 中图片不被压缩的方法 法1&#xff1a; 调节word 选项中的图片格式为不压缩、高保真 法2&#xff1a; 1: word 中的图片尽可能使用高的分辨率&#xff0c;图片存为pnd或者 tif 格式&#xff08;最高清&#xff09; 2: 转化为pdf使用打印机器&#xff0c;参数如下…

【ubuntu】切换shell并显示git分支名字

y9kp 显示当前shell echo $SHELLwhich bash根据输出&#xff0c;例如 /bin/bash 改变shell&#xff1a; chsh -s /bin/bash退出重新登录 加入函数及覆盖PS1 # Function to return the current Git branch name git_branch() {# Check if the current directory is in a Git …