2016-04-26 30 views
0

我正在写一个应用程序,允许用户添加项目到场景。我不希望任何新项目被绘制在已经绘制的项目上,并且我决定使用collidesWithItem()函数来检测碰撞。与我的代码,我仍然可以绘制添加项目,即使有明显的碰撞,我调试程序和collidesWithItem()函数不断返回“False”。collidesWithItem()函数不检测碰撞(PyQt)

通过单击表单的工具栏添加项目。楼下

是我的代码:

class graphicsScene(QtGui.QGraphicsScene, QtGui.QWidget): 
    def __init__(self, parent=None): 
     super(graphicsScene, self).__init__(parent) 
     self.i = 0 
     self.setSceneRect(-180, -90, 360, 180) 
     global overlapped 
     overlapped = 0 

    def mousePressEvent(self, event): 
     global host_cs 
     global overlapped 

     if host_cs == 1: 
      if len(hostItem_list) == 0: 
       self.host_item = host_Object() 
       hostItem_list.append(self.host_item.host_pixItem) 
      else: 
       self.host_item = host_Object() 
       for host in hostItem_list: 
        if self.host_item.host_pixItem.collidesWithItem(host): 
         print 'collision' 
         overlapped = 1 
         break 

        elif self.host_item.host_pixItem.collidesWithItem(host) == False: 
         overlapped = 0 
         if overlapped == 0: 
          hostItem_list.append(self.host_item.host_pixItem) 

    def mouseReleaseEvent(self, event): 
     global host_cs 
     if host_cs == 1: 
      if overlapped == 0: 
       self.addItem(self.host_item.host_pixItem) 
       self.host_item.host_pixItem.setPos(event.scenePos()) 
       self.i += 1 
       host_list.append('h' + str(self.i)) 

class host_Object(QtGui.QGraphicsPixmapItem, QtGui.QWidget): 
    def __init__(self, parent=None): 
     super(host_Object, self).__init__(parent) 
     pixmap = QtGui.QPixmap("host.png") 
     self.host_pixItem = QtGui.QGraphicsPixmapItem(pixmap.scaled(30, 30, QtCore.Qt.KeepAspectRatio)) 
     self.host_pixItem.setFlag(QtGui.QGraphicsPixmapItem.ItemIsSelectable) 
     self.host_pixItem.setFlag(QtGui.QGraphicsPixmapItem.ItemIsMovable) 

class Form(QtGui.QMainWindow, QtGui.QWidget): 
    def __init__(self): 
     super(Form, self).__init__() 
     self.ui = uic.loadUi('form.ui') 

     self.ui.actionHost.triggered.connect(self.place_host) 

     self.scene = graphicsScene() 
     self.ui.view.setScene(self.scene) 

    def place_host(self): 
     host_cs = 1 

if __name__ == '__main__': 

    app = QtGui.QApplication(sys.argv) 
    form = Form() 
    form.ui.show() 
    app.exec_() 
+0

'class host_Object(QtGui.QGraphicsPixmapItem,QtGui.QWidget)'它是什么?这是禁止的!你不能像这样继承。这可能是你的问题的根源。同样在这里:'class Form(QtGui.QMainWindow,QtGui.QWidget)'。 –

回答

0

多重继承是在应用程序设计的所有邪恶的东西源。 另外它在Qt中被禁止双重继承QObject。所以你所有的具有多重继承的类都有很大的缺陷。

即使class host_Object(QtGui.QGraphicsPixmapItem, QtGui.QWidget)是错误的并且有问题,因为项目不能同时为QWidgetQGraphicsItem

我会建议你避免双重继承作为一般规则不仅Qt框架,但任何语言。

+0

谢谢你的回复,我删除了第二个不必要的继承,但程序仍然没有检测到碰撞。这是什么原因? – neziy