collidesWithItem()函数未检测到碰撞(PyQt)

时间:2016-04-26 19:24:47

标签: python qt pyqt

我正在编写一个允许用户向场景添加项目的应用程序。我不希望在已经绘制的项目上绘制任何新项目,并且为此我决定使用collidesWithItem()函数来检测碰撞。使用我的代码我仍然可以绘制添加的项目,即使有明显的冲突,我调试了程序,并且collidesWithItem()函数继续返回" False"。

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

下面是我的代码:

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_()

1 个答案:

答案 0 :(得分:0)

多重继承是应用程序设计中所有邪恶事物的来源。 在Qt中禁止双重继承QObject。 因此,所有具有多重继承的类都存在很大的缺陷。

即使class host_Object(QtGui.QGraphicsPixmapItem, QtGui.QWidget)错误也有问题,因为商品不能同时为QWidgetQGraphicsItem

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