QGraphicsView拖放问题

时间:2015-08-28 19:53:03

标签: python qt pyqt

我遇到PyQt4 GraphicsView的问题。我想使用从listview拖放到图形场景/视图中,并将项目准确放置在鼠标光标的位置。

from PyQt4 import QtCore, QtGui
import sys

class GraphicsScene(QtGui.QGraphicsScene):

    def __init__(self, parent = None):
        super(GraphicsScene, self).__init__(parent)

    def dragEnterEvent(self, event):
        event.accept()

    def dragMoveEvent(self, event):
        event.accept()

    def dragLeaveEvent(self, event):
        event.accept()

    def dropEvent(self, event):
        text = QtGui.QGraphicsTextItem(event.mimeData().text())
        text.setPos(event.scenePos())
        self.addItem(text)
        event.accept()

class ListView(QtGui.QListView):

    def __init__(self, parent = None):
        super(ListView, self).__init__(parent)
        self.setDragEnabled(True)

    def dragEnterEvent(self, event):
        event.setDropAction(QtCore.Qt.MoveAction)
        event.accept()

    def startDrag(self, event):
        index = self.indexAt(event.pos())
        if not index.isValid():
            return

        selected = self.model().data(index, QtCore.Qt.DisplayRole)

        mimeData = QtCore.QMimeData()
        mimeData.setText(selected.toString())

        drag = QtGui.QDrag(self)
        drag.setMimeData(mimeData)

        result = drag.start(QtCore.Qt.MoveAction)
        if result: # == QtCore.Qt.MoveAction:
            pass

    def mouseMoveEvent(self, event):
        self.startDrag(event)

class MainWindow(QtGui.QMainWindow):

    def __init__(self, parent = None):
        super(MainWindow, self).__init__(parent)

        self.setGeometry(100, 100, 400, 400)

        self.widget = QtGui.QWidget()
        self.setCentralWidget(self.widget)
        layout = QtGui.QGridLayout(self.widget)

        self.ListView = ListView()

        data = QtCore.QStringList()
        data << "one" << "two" << "three"
        self.model = QtGui.QStringListModel(data)

        self.ListView.setModel(self.model)

        self.GraphicsView = QtGui.QGraphicsView()
        self.scene = GraphicsScene()
        self.GraphicsView.setScene(self.scene)

        layout.addWidget(self.ListView, 0, 0, 5, 5)
        layout.addWidget(self.GraphicsView, 0, 1, 5, 5)

        self.show()

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec_())

放弃第一个项目时出现问题。它直接进入视图中心,但我希望它保持在光标位置。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

看起来你需要先设置QGraphicsView的rect来正确初始化它。然后添加的第一个项目将按预期工作。

self.GraphicsView.setSceneRect(0, 0, self.GraphicsView.width(), self.GraphicsView.height())

这需要在show事件之后添加,因为调用QGraphicsView的宽度和高度会事先抛出错误的值。