【问题标题】:Why is my QGraphicsItem not selectable?为什么我的 QGraphicsItem 不可选择?
【发布时间】:2015-01-02 15:59:23
【问题描述】:

我复制了一些代码 sn-ps 并制作了我自己的版本。最初的 sn-p(我不再拥有)允许移动并选择 QgraphicsItem。我的修改版本允许移动,但不允许选择。我做错了什么?

#!d:/python27/python -u

import sys
from PyQt4 import QtGui, QtCore

class GraphicsItem(QtGui.QGraphicsItem):
    #
    # QtGui.QGraphicsItem always needs to override its two public abstract methods
    # paint, boundingRect
    #
    def __init__(self, rect=None, parent=None):
        super(GraphicsItem, self).__init__(parent)

        self.setFlag(QtGui.QGraphicsItem.ItemIsMovable, True)
        self.setFlag(QtGui.QGraphicsItem.ItemIsSelectable, True)

        self.pen = QtGui.QPen(QtCore.Qt.SolidLine)
        self.pen.setColor(QtCore.Qt.blue)
        self.pen.setWidth(8)
        self.brush = QtGui.QBrush(QtCore.Qt.red)

        self.rect = QtCore.QRectF(rect[0], rect[1], rect[2], rect[3])

    def mouseMoveEvent(self, event):
        # move object
        QtGui.QGraphicsItem.mouseMoveEvent(self, event)

    def boundingRect(self):
        return self.rect

    def paint(self, painter, option, widget):
        painter.setBrush(self.brush)
        painter.setPen(self.pen)
        painter.drawEllipse(self.rect)


class MyMainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__(parent)

        width = 1000
        height = 800
        scene = QtGui.QGraphicsScene(-width/2, -height/2, width, height)

        graphicsItem = GraphicsItem((-100, -100, 200, 200))
        scene.addItem(graphicsItem)

        view = QtGui.QGraphicsView()
         # set QGraphicsView attributes
        view.setRenderHints(QtGui.QPainter.Antialiasing |
                            QtGui.QPainter.HighQualityAntialiasing)
        view.setViewportUpdateMode(QtGui.QGraphicsView.FullViewportUpdate)

        view.setScene(scene)
        self.setCentralWidget(view)

    def keyPressEvent(self, event):
        key = event.key()

        if key == QtCore.Qt.Key_Escape:
            sys.exit(QtGui.qApp.quit())
        else:
            super(GraphicsView, self).keyPressEvent(event)

def main():
    app = QtGui.QApplication(sys.argv)
    form = MyMainWindow()
    form.setGeometry(700, 100, 1050, 850)
    form.show()
    app.exec_()

if __name__ == '__main__':
    main()

【问题讨论】:

    标签: python pyqt4


    【解决方案1】:

    你在类 GraphicsItem 中错过了这个方法:

    def mousePressEvent(self, event):
        # select object
        QtGui.QGraphicsItem.mousePressEvent(self, event)
        print (self) # show the selected item
    

    【讨论】:

    • 非常感谢。显然我删的太多了。
    • 附加问题:当项目被选中时,它显示了一个虚线的有界矩形。这个怎么设置?我必须自己画吗?
    • 您可以在您的绘画方法中定义一个选项。但是,请通过适当的例子将其作为一个新问题提出:)
    • 完成。This is the link.
    猜你喜欢
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    • 2016-06-30
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 2010-11-12
    • 2018-10-31
    相关资源
    最近更新 更多