QRectF 没有出现在我的 QGraphicsScene 中

QRectF doesn't appear in my QGraphicsScene

我正在尝试使用 QGraphicsView(在 Maya 中)并获得一些代码,我将在下面粘贴这些代码。问题是 window QGraphicsView 来了,但看起来 QGraphicsScene(和我的 QRectF)没有来。我仍然对继承的工作方式感到困惑,所以有人可以指出我哪里做错了。谢谢。

from PySide2 import QtGui, QtCore, QtWidgets
from shiboken2 import wrapInstance
import maya.OpenMaya as om
import maya.OpenMayaUI as omui
import maya.cmds as cmds
import os, functools


def getMayaWindow():
    pointer = omui.MQtUtil.mainWindow()
    if pointer is not None:
        return wrapInstance(long(pointer), QtWidgets.QWidget)


class testUi(QtWidgets.QDialog):
    def __init__(self, parent=None):  
        if parent is None:
            parent = getMayaWindow()
        super(testUi, self).__init__(parent) 
        self.window = 'vl_test'
        self.title = 'Test Remastered'
        self.size = (1000, 650)

        self.create() 

    def create(self):
        if cmds.window(self.window, exists=True):
            cmds.deleteUI(self.window, window=True)

        self.setWindowTitle(self.title)
        self.resize(QtCore.QSize(*self.size))
        self.testik = test(self)  

        self.mainLayout = QtWidgets.QVBoxLayout() 
        self.mainLayout.addWidget(self.testik)
        self.setLayout(self.mainLayout) 


class test(QtWidgets.QGraphicsView):

    def __init__(self, parent=None):
        super(test, self).__init__(parent) 

        self._scene = QtWidgets.QGraphicsScene() 
        rect_item = QtWidgets.QGraphicsRectItem(QtCore.QRectF(0, 0, 100, 100))
        rect_item.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable, True)
        self._scene.addItem(rect_item) 

v = testUi()
v.show()

问题是您没有将 QGraphicsScene 添加到 QGraphicsView:

class test(QtWidgets.QGraphicsView):
    def __init__(self, parent=None):
        super(test, self).__init__(parent) 
        self._scene = QtWidgets.QGraphicsScene() 
        self.setScene(self._scene) # <---
        rect_item = QtWidgets.QGraphicsRectItem(QtCore.QRectF(0, 0, 100, 100))
        rect_item.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable, True)
        self._scene.addItem(rect_item) 

Eyllanesc 是正确的,您已经创建了一个 QGraphicsScene,但您仍然需要将其设置为 QGraphicsView

查看 QGraphicsView's constructor 的文档,您还可以通过其 __init__ 参数之一传递场景:QGraphicsView.__init__ (self, QGraphicsScene scene, QWidget parent = None)

因此您可以保存一行并将其直接传递给您的 class 的 super:

class test(QtWidgets.QGraphicsView):

    def __init__(self, scene, parent=None):
        self._scene = QtWidgets.QGraphicsScene()  # Create scene first.

        super(test, self).__init__(self._scene, parent)  # Pass scene to the QGraphicsView's constructor method.

        rect_item = QtWidgets.QGraphicsRectItem(QtCore.QRectF(0, 0, 100, 100))
        rect_item.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable, True)
        self._scene.addItem(rect_item)