2016-04-26 584 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