gpt4 book ai didi

python - QGraphicsView拖放问题

转载 作者:太空宇宙 更新时间:2023-11-03 17:28:15 25 4
gpt4 key购买 nike

我对 PyQt4 GraphicsView 有问题。我想使用从 ListView 拖放到图形场景/ View 中并将项目精确放置在鼠标光标的位置。

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

删除第一个项目时出现问题。它直接进入 View 中心,但我希望它停留在光标位置。有什么想法吗?

最佳答案

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

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

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

关于python - QGraphicsView拖放问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32278845/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com