AttributeError:“ NoneType”对象没有属性“ scenePos”

时间:2018-11-26 05:16:40

标签: python python-2.7 pyqt pyqt4 qgraphicsview

这是我的示例代码,我想通过使用鼠标按下事件来打印x,y位置的我的坐标,我得到了这个错误,请问有人可以帮助我,我想在中间显示我的图形视图吗? scrollArea。

下面是我的代码:

from pyface.qt import QtGui, QtCore
import sys

class MyView(QtGui.QGraphicsView):
    def __init__(self):
        QtGui.QGraphicsView.__init__(self)
        self.row = 2
        self.cols = 4
        self.scene = QtGui.QGraphicsScene(0,0,500,500)
        self.List = []

        for i in range(self.row):
            for j in range(self.cols):
                item = self.scene.addRect(QtCore.QRectF(0,0,30,30))
                item.setPos(30+j*30,500-i*30-60)
                print item.scenePos()
                self.List.append(item)
        self.setScene(self.scene)
    def mousePressEvent(self,event):
        super(MyView,self).mousePressEvent(event)
        p = QtCore.QPointF(event.pos())
        print "positonnnnnnnnnnnnnnnn", p
        item = self.scene.itemAt(p)
        print "@@@@@@@@@@@@@@@@@@@@@@@@@2"
        print item.scenePos()
class Settings(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(Settings, self).__init__(parent)
        spacer = QtGui.QWidget(self)
        spacer.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        QtGui.QToolTip.setFont(QtGui.QFont('SansSerif', 10))
        self.vbox = QtGui.QVBoxLayout()
        self.save = QtGui.QPushButton("save")
        self.open= QtGui.QPushButton("open")
        self.folder= QtGui.QPushButton("Folder")
        self.folder.clicked.connect(self.showSettings)
        self.vbox.addWidget(self.save)
        self.vbox.addWidget(self.open)
        self.vbox.addWidget(self.folder)
        self.grid = QtGui.QGridLayout()
        self.grid.addLayout(self.vbox,0,0)
        self.scrollArea = QtGui.QScrollArea()
        self.scrollArea.setBackgroundRole(QtGui.QPalette.Light)
        self.scrollArea.setWidgetResizable(True)
        self.grid.addWidget(self.scrollArea,0,1)
        self.setCentralWidget(QtGui.QWidget(self))
        self.centralWidget().setLayout(self.grid)
        self.setGeometry(200,100,300,300)
        self.show()
    def showSettings(self):
        self.newwidget = QtGui.QWidget()
        self.glayout = QtGui.QGridLayout(self.newwidget)
        self.MyView =  MyView()
        self.glayout.addWidget(self.MyView,0,1)
        self.scrollArea.setWidget(self.newwidget)
def main():
    app = QtGui.QApplication(sys.argv)
    ex = Settings()
    sys.exit(app.exec_())
if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:1)

event.pos()返回鼠标相对于viewport的{​​{1}}的位置的情况下,项目的坐标与窗口的坐标不同。将必须使用QGraphicsView将其转换为场景的坐标,另一方面,使用mapToScene()时可能返回None,因为在场景的某些区域中没有任何项目,因此建议进行验证

itemAt()

要了解处理QGraphicsView,QGraphicsScene和QGraphicsItems的不同坐标系,建议阅读Graphics View Framework