QT C++在2D图形方面已经做的很完善了,在PC端(Windows、Linux和MaC)上都有很好的表现。

QT中的QML特别适合于移动端应用的开发,QML中的一些基本形状类型并不是一一地与Qt C++相对应,但是通过C++可以来扩展QML。

QQuickPaintedItem继承自QQuickItem,提供了使用QPainter API的方法来扩展QML中的2D图形项。

QQuickPaintedItem没有像QGraphicsItem那样提供shape()方法来获取图形项的具体实际形状,但是其包含contains()方法,我们可以间接地结合鼠标操作点来判断是否包含在实际形状范围内。

废话不多说,直接上测试代码:

CustomItem.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
 
#ifndef CUSTOMITEM_H
#define CUSTOMITEM_H

#include <QQuickPaintedItem>
#include <QQuickItem>
#include <QMouseEvent>
#include <QPainter>

class CustomItem : public QQuickPaintedItem
{
    Q_OBJECT
    Q_PROPERTY(QString name READ name WRITE setName)
    Q_PROPERTY(QColor color READ color WRITE setColor)

public:
    CustomItem(QQuickItem *parent = nullptr);

QString name() const;
    void setName(const QString &name);

QColor color() const;
    void setColor(const QColor &color);

// override paint() for actual painting.
    virtual void paint(QPainter *painter);
    // override contans() for shape mask, Q_INVOKABLE for QML use.
    Q_INVOKABLE virtual bool contains(const QPointF &point) const;

virtual void mousePressEvent(QMouseEvent *event);
    virtual void mouseMoveEvent(QMouseEvent *event);
    virtual void mouseReleaseEvent(QMouseEvent *event);

private:
    QString m_name;
    QColor m_color;
};

#endif // CUSTOMITEM_H

 CustomItem.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
 
#include "CustomItem.h"
#include <QPainter>
#include <QPainterPathStroker>
#include <QDebug>

CustomItem::CustomItem(QQuickItem *parent)
    : QQuickPaintedItem(parent)
{
    setAcceptedMouseButtons(Qt::LeftButton
                            | Qt::RightButton
                            | Qt::MiddleButton);
    setFlag(QQuickItem::ItemHasContents);
}

QString CustomItem::name() const
{
    return m_name;
}

void CustomItem::setName(const QString &name)
{
    m_name = name;
}

QColor CustomItem::color() const
{
    return m_color;
}

void CustomItem::setColor(const QColor &color)
{
    m_color = color;
}

void CustomItem::paint(QPainter *painter)
{
    // pen & brush
);
    QLinearGradient gradient;
    gradient.setStart();
    gradient.setFinalStop();
    gradient.setColorAt(, Qt::blue);
    gradient.setColorAt(, Qt::green);
    gradient.setColorAt(, Qt::red);
    gradient.setColorAt(, Qt::yellow);
    gradient.setColorAt(, Qt::cyan);
    painter->setPen(pen);
    painter->setBrush(gradient);
    painter->setRenderHints(QPainter::Antialiasing, true);

// Unclosed shape
] =
    {
        QPointF(),
        QPointF(),
        QPointF(),
    };

painter->save();
    pen.setJoinStyle(Qt::MiterJoin);    // MiterJoin, BevelJoin, RoundJoin
    pen.setCapStyle(Qt::RoundCap);      // FlatCap, SquareCap, RoundCap
    pen.setStyle(Qt::DashLine);
    painter->drawPolyline(points, );
    painter->restore();

// Closed shape
    QPainterPath path;
    path.addEllipse(QRectF());
    painter->drawPath(path);

/* 三角形
    QPainterPath path;
    path.moveTo(width() / 2, 0);
    path.lineTo(width(), height());
    path.lineTo(0, height());
    path.lineTo(width() / 2, 0);
    painter->fillPath(path, m_color);
    */
}

bool CustomItem::contains(const QPointF &point) const
{
    // Unclosed shape
] =
    {
        QPointF(),
        QPointF(),
        QPointF(),
    };
    QPainterPath path;
    path.moveTo(points[]);
    path.lineTo(points[]);
    path.lineTo(points[]);
    QPainterPathStroker stroker;
    stroker.setWidth();
    stroker.setJoinStyle(Qt::MiterJoin);
    stroker.setCapStyle(Qt::RoundCap);
    stroker.setDashPattern(Qt::SolidLine);
    return stroker.createStroke(path).contains(point);

// Close shape
    QPainterPath path;
    path.addEllipse(QRectF());
    QPainterPathStroker stroker;
    stroker.setWidth();
    return path.contains(point) || stroker.createStroke(path).contains(point);

/* 三角形
    QPainterPath path;
    path.moveTo(width() / 2, 0);
    path.lineTo(width(), height());
    path.lineTo(0, height());
    path.lineTo(width() / 2, 0);
    QPainterPathStroker stroker;
    stroker.setWidth(10);
    return return path.contains(point) || stroker.createStroke(path).contains(point);
    */
}

void CustomItem::mousePressEvent(QMouseEvent *event)
{
    qDebug() << "CustomItem::mousePressEvent";
    QQuickPaintedItem::mousePressEvent(event);
}

void CustomItem::mouseMoveEvent(QMouseEvent *event)
{
    qDebug() << "CustomItem::mouseMoveEvent";
    QQuickPaintedItem::mouseMoveEvent(event);
}

void CustomItem::mouseReleaseEvent(QMouseEvent *event)
{
    qDebug() << "CustomItem::mouseReleaseEvent";
    QQuickPaintedItem::mouseReleaseEvent(event);
}

在main.cpp中注册CustomItem类型:qmlRegisterType<CustomItem>("CustomItem", 1, 0, "CustomItem");

 main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "CustomItem.h"

int main(int argc, char *argv[])
{
    qputenv("QT_IM_MODULE", QByteArray("qtvirtualkeyboard"));

QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

QGuiApplication app(argc, argv);

qmlRegisterType<CustomItem>(, "CustomItem");

QQmlApplicationEngine engine;
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject * obj, const QUrl & objUrl)
    {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-);
    }, Qt::QueuedConnection);
    engine.load(url);

return app.exec();
}

在qml文件中使用:

 main.qml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
 

Window {
    id: window
    visible: true
    width: 
    height: 
    title: qsTr("qml-2d-viewer")

Button {
        id: btn
        anchors.right: parent.right
        anchors.bottom: parent.bottom
        text: "Populate"
        onClicked: {
            var object = Qt.createQmlObject(
                        'import QtQuick 2.12;
;
                         CustomItem {
                            width: 
                            height: 
                            x: window.width * Math.random()
                            y: window.height * Math.random()
                            name: "A simple Rectangle Item"
                            color: Qt.rgba(Math.random(), Math.random(), Math.random(), )

MouseArea {
                                anchors.fill: parent
                                onPressed: {
                                    if (parent.contains(Qt.point(mouse.x, mouse.y))){
                                        drag.target = parent
                                        parent.color = Qt.rgba(Math.random(), Math.random(), Math.random(), );
                                        parent.update();
                                    }
                                    else{
                                        drag.target = null
                                    }
                                }
                                drag.axis: Drag.XAndYAxis
                                drag.minimumX: 
                                drag.maximumX: window.width - parent.width
                                drag.minimumY: 
                                drag.maximumY: window.height - parent.width
                                }
                            }',
                        parent,
                        "dynamicSnippet");
        }
    }

// QML Rectangle Type
    Rectangle {
        id: blueSquare
        width: 
        x: window.width - width -     // making this item draggable, so don't use anchors
        color: "blue"
        visible: false

Text { text: ; color: "white"; anchors.centerIn: parent }

MouseArea {
            anchors.fill: parent
            //! [drag]
            drag.target: blueSquare
            drag.axis: Drag.XAndYAxis
            drag.minimumX: 
            drag.maximumX: window.width - parent.width
            drag.minimumY: 
            drag.maximumY: window.height - parent.width
            //! [drag]
        }
    }

// CustomItem Type Inherited from QQuickPaintedItem
    CustomItem {
        id: aRectangle
        width: 
        height: 
        name: "A simple Rectangle Item"
        color: "red"

MouseArea {
            anchors.fill: parent
            onPressed: {
                if (parent.contains(Qt.point(mouse.x, mouse.y))){
                    drag.target = parent
                    parent.color = Qt.rgba(Math.random(), Math.random(), Math.random(), );
                    parent.update();
                }
                else{
                    drag.target = null
                }
            }
            drag.axis: Drag.XAndYAxis
            drag.minimumX: 
            drag.maximumX: window.width - parent.width
            drag.minimumY: 
            drag.maximumY: window.height - parent.width
        }
    }
}

Q_INVOKABLE宏将contains()方法注册到元对象系统中,这样QML就可以调用该方法来判断鼠标指针点是否在图形项形状区域,从而实现精准拾取。

在QML中MouseArea为简单的鼠标交互提供了方便,比较容易使用,如果有了MouseArea,则C++中的鼠标响应事件就不再响应。

QQuickPaintedItem鼠标精准拾取(pick/select)研究的更多相关文章

  1. QGraphicsItem鼠标精准拾取(pick/select)研究

    在QT场景视图中,一个2D图形项是一个QGraphicsItem,我们可以通过继承来定义我们自己的图形项. 主要有以下三个虚函数需要重点关注: 1)   边界矩形(必须实现) virtual QRec ...

  2. Micro LED巨量转移技术研究进展

    近年来,Micro LED因其功耗低.响应快.寿命长.光效率高等特点,被视为继LCD.OLED之后的新一代显示面板技术.Micro LED的英文全名是Micro Light Emitting Diod ...

  3. OpenGL中的拾取模式( Picking)

    1. Opengl中的渲染模式有三种:(1)渲染模式,默认的模式:(2)选择模式, (3)反馈模式.如下 GLint glRenderMode(GLenum mode) mode可以选取以下三种模式之 ...

  4. Selenium:利用select模块处理下拉框

    在利用selenium进行UI自动化测试过程中,经常会遇到下拉框选项,这篇博客,就介绍下如何利用selenium的Select模块来对标准select下拉框进行操作... 首先导入Select模块: ...

  5. js实现鼠标拖动框选元素小狗

    方法一: <html> <head></head> <style> body{padding:100px;} .fileDiv{float:left;w ...

  6. WebGL射线拾取模型——八叉树优化

    经过前面2篇WebGL射线拾取模型的文章,相信大家对射线和模型面片相交的原理已经有所了解,那么今天我们再深入探究关于射线拾取的一个问题,那就是遍历场景中的所有与射线相交的模型的优化问题.首先我们来复习 ...

  7. 微软的鼠标 Microsoft mouse

    微软是做软件出身的厂商, 所以微软开发的软件质量毋庸置疑,Windows操作系统还有诸如Office的办公软件拥有庞大的用户群. 微软家的Visual Studio也被号称宇宙最强IDE,我个人也每天 ...

  8. Selenium: 利用select模块操作下拉框

    在利用selenium进行UI自动化测试过程中,经常会遇到下拉框选项,这篇博客,就介绍下如何利用selenium的Select模块来对标准select下拉框进行操作... 首先导入Select模块: ...

  9. 转:SDL2源代码分析

    1:初始化(SDL_Init()) SDL简介 有关SDL的简介在<最简单的视音频播放示例7:SDL2播放RGB/YUV>以及<最简单的视音频播放示例9:SDL2播放PCM>中 ...

随机推荐

  1. pipenv安装包时一直卡在Locking [packages] dependencies…,换pypi源

    Pipfile 中 source 源是 python 官网,服务器在国外,加载比较慢. 将 url 修改为清华的 pypi 源 https://pypi.tuna.tsinghua.edu.cn/si ...

  2. mybatis框架之多参数入参--传入Map集合

    需求:查询出指定性别和用户角色列表下的用户列表信息 实际上:mybatis在入参的时候,都是将参数封装成为map集合进行入参的,不管你是单参数入参,还是多参数入参,都是可以封装成map集合的,这是无可 ...

  3. zzL4自动驾驶中感知系统遇到的挑战及解决方案

    本次分享的大纲: Perception Introduction Sensor Setup & Sensor Fusion Perception Onboard System Percepti ...

  4. Linux性能优化实战学习笔记:第四十三讲

    一.上节回顾 上一节,我们了解了 NAT(网络地址转换)的原理,学会了如何排查 NAT 带来的性能问题,最后还总结了 NAT 性能优化的基本思路.我先带你简单回顾一下. NAT 基于 Linux 内核 ...

  5. [LeetCode] 857. Minimum Cost to Hire K Workers 雇佣K名工人的最低成本

    There are N workers.  The i-th worker has a quality[i] and a minimum wage expectation wage[i]. Now w ...

  6. [比赛题解]CWOI2019-1

    [比赛题解]CWOI2019-1 比赛日期:2019.10.12 T1 一道神仙DP题. 我们考虑\(dp[i][j][k]\)表示最后\(i\)位数,\(i-1\)位都是9,最后一位为\(j\),最 ...

  7. Python连载31-threading的使用

    一. 例子:我们对传参是有要求的必须传入一个元组,否则报错 二. import _thread as thread import time def loop1(in1): print("St ...

  8. Python 遍历目录下的子目录和文件

    import os A: 遍历目录下的子目录和文件 for root,dirs ,files in os.walk(path) root:要访问的路径名 dirs:遍历目录下的子目录 files:遍历 ...

  9. Flink及Storm、Spark主流流框架比较

    转自:http://www.sohu.com/a/142553677_804130 引言 随着大数据时代的来临,大数据产品层出不穷.我们最近也对一款业内非常火的大数据产品 - Apache Flink ...

  10. SQL-----数据库三种删除方式详解

    第一种  使用delete  语句 特点: delete 属于数据库操纵语言DML,表示删除表中的数据, 删除过程是每次从表中删除一行,并把该行删除操作作为事务记录在日志中保存 可以配合事件(tran ...