新网创想网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

【PyQt】运行QGraphicsItem的Demo代码-创新互联

这属于研究和测试Qt5文档中QGraphicsItem的脚手架代码。

创新互联是一家集网站建设,蓝田企业网站建设,蓝田品牌网站建设,网站定制,蓝田网站建设报价,网络营销,网络优化,蓝田网站推广为一体的创新建站企业,帮助传统企业提升企业形象加强企业竞争力。可充分满足这一群体相比中小企业更为丰富、高端、多元的互联网需求。同时我们时刻保持专业、时尚、前沿,时刻以成就客户成长自我,坚持不断学习、思考、沉淀、净化自己,让我们为更多的企业打造出实用型网站。

在查看Qt5中 QGraphicsItem 类的帮助文档时,为了上手验证文档中的代码,需要一个完整的可运行的 PyQt5 代码框架。我自己改编了一份,尽量短小高效。

该代码在配置了pyqt5、pyqt5-tools等代码库的PyCharm中可运行。(如何配置PyQt,见此文)

1 目的

运行 QPainterPath 文档里的C++代码。

该文档只列出如下的C++代码片段,无法直接运行,于是整理出Demo框架,后续将代码片段粘贴到 painter 函数里就能查看代码的运行效果。

QPainterPath path;
path.addRect(20, 20, 60, 60);

path.moveTo(0, 0);
path.cubicTo(99, 0,  50, 50,  99, 99);
path.cubicTo(0, 99,  50, 50,  0, 0);

QPainter painter(this);
painter.fillRect(0, 0, 100, 100, Qt::white);
painter.setPen(QPen(QColor(79, 106, 25), 1, Qt::SolidLine,
                    Qt::FlatCap, Qt::MiterJoin));
painter.setBrush(QColor(122, 163, 39));

painter.drawPath(path);
2 运行效果

3. Demo框架
# ***************************************************************************
# * Copyright (c) 2022,*
# ***************************************************************************
# """ test qt5 example demo """

import sys
from PyQt5.QtGui import QPainterPath, QColor, QPen
from PyQt5.QtWidgets import QApplication, QGraphicsView, QGraphicsScene, QMainWindow, QGraphicsItem
from PyQt5.QtCore import Qt, QRectF

# 自定义图元
class MyItem(QGraphicsItem):
    def __init__(self):
        super().__init__()

    # 必须实现的两个方法 painter 和 boundingRect
    def paint(self, painter, option, widget):
        # 这里可以替换为你要测试的代码
        path = QPainterPath()
        path.addRect(20, 20, 60, 60)
        path.moveTo(0, 0)
        path.cubicTo(99, 0,  50, 50,  99, 99)
        path.cubicTo(0, 99,  50, 50,  0, 0)

        painter.fillRect(0, 0, 100, 100, QColor("white"))
        painter.setPen(QPen(QColor(79, 106, 25), 1, Qt.SolidLine, Qt.FlatCap, Qt.MiterJoin))
        painter.setBrush(QColor("Green"))
        painter.drawPath(path)

    def boundingRect(self):
        return QRectF(0, 0, 100, 100)


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.scene = QGraphicsScene()

        item = MyItem()
        self.scene.addItem(item)

        # 有view就要有scene
        self.view = QGraphicsView()
        self.view.setScene(self.scene)

        # 设置view可以进行鼠标的拖拽选择
        self.view.setDragMode(self.view.RubberBandDrag)

        self.setMinimumHeight(500)
        self.setMinimumWidth(500)
        self.setCentralWidget(self.view)
        self.setWindowTitle("Graphics Demo")


def demo_run():
    app = QApplication(sys.argv)
    demo = MainWindow()
    # 适配 Retina 显示屏(选写).
    app.setAttribute(Qt.AA_UseHighDpiPixmaps, True)
    app.setAttribute(Qt.AA_EnableHighDpiScaling, True)
    # ----------------------------------
    demo.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    demo_run()
4 增强版

这个版本通过创建自定义的QGraphicsView子类,实现按键、鼠标响应,可自己补充实现用户按下按键或者鼠标点击后的功能。

# ***************************************************************************
# * Copyright (c) 2022,*
# ***************************************************************************
# """ test qt5 example demo """

import sys
import traceback

from PyQt5.QtGui import QPainterPath, QColor, QPen, QKeyEvent
from PyQt5.QtWidgets import QApplication, QGraphicsView, QGraphicsScene, QMainWindow, QGraphicsItem
from PyQt5.QtCore import Qt, QRectF


class MyItem(QGraphicsItem):
    """ 自定义图元 """
    def __init__(self):
        super().__init__()

    # 必须实现的两个方法 painter 和 boundingRect
    def paint(self, painter, option, widget):
        # 这里可以替换为你要测试的代码
        path = QPainterPath()
        path.addRect(20, 20, 60, 60)
        path.moveTo(0, 0)
        path.cubicTo(99, 0,  50, 50,  99, 99)
        path.cubicTo(0, 99,  50, 50,  0, 0)

        painter.fillRect(0, 0, 100, 100, QColor("white"))
        painter.setPen(QPen(QColor(79, 106, 25), 1, Qt.SolidLine, Qt.FlatCap, Qt.MiterJoin))
        painter.setBrush(QColor("Green"))
        painter.drawPath(path)

    def boundingRect(self):
        return QRectF(0, 0, 100, 100)


class MyView(QGraphicsView):
    """ 自定义视图类,可实现按键、鼠标触发自定义事件 """
    def __init__(self):
        super().__init__()

    # override
    def keyPressEvent(self, event):
        try:
            super().keyPressEvent(event)
            if event.key() == Qt.Key_N:
                print("按下键盘N键")
        except Exception:
            traceback.print_exc()  # 可打印错误行号,异常的详细内容

    # override
    def mousePressEvent(self, event):
        try:
            super().mousePressEvent(event)
            if event.button() == Qt.RightButton:  # 判断鼠标右键点击
                item = self.itemAt(event.pos())
                if isinstance(item, MyItem):  # 判断点击对象是否为图元的实例
                    print("鼠标右键点击了自定义图元")
        except Exception:
            traceback.print_exc()

# 主窗口
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        item = MyItem()
        self.scene = QGraphicsScene()
        self.scene.addItem(item)

        self.view = MyView()            # 使用自定义的View,不使用Qt的View
        self.view.setScene(self.scene)

        # 设置view可以进行鼠标的拖拽选择
        self.view.setDragMode(self.view.RubberBandDrag)
        self.setMinimumHeight(500)
        self.setMinimumWidth(500)
        self.setCentralWidget(self.view)
        self.setWindowTitle("Graphics Demo")


def demo_run():
    app = QApplication(sys.argv)
    demo = MainWindow()
    # 适配 Retina 显示屏(选写).
    app.setAttribute(Qt.AA_UseHighDpiPixmaps, True)
    app.setAttribute(Qt.AA_EnableHighDpiScaling, True)
    # ----------------------------------
    demo.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    demo_run()

5 其他

使用PyQt,还是需要查阅 Qt 的官方文档。如果想运行文档中的代码,那就需要自己将Qt文档中的 C++ 代码改成 Python 代码。不过也比较简单,PyQt只是对Qt简单的进行了包装,参数都还是按照原C++的函数参数设置的,只是原C++中的 Qt::SolidLine 这些枚举常量基本都变成了  Qt.SolidLine,即塞到了Qt包中。

你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧


新闻标题:【PyQt】运行QGraphicsItem的Demo代码-创新互联
标题路径:http://www.wjwzjz.com/article/dcgihs.html
在线咨询
服务热线
服务热线:028-86922220
TOP