QRectF没有出现在我的QGraphicsScene中

时间:2019-04-04 06:28:33

标签: python maya qgraphicsview qgraphicsscene pyside2

我正在尝试使用QGraphicsView(在Maya中)并得到一些代码,将在下面粘贴。问题是带有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()

2 个答案:

答案 0 :(得分:2)

问题是您尚未将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) 

答案 1 :(得分:2)

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

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

因此您可以保存一行并将其设置为直接将其传递到您班级的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)