我正在努力让拖放工作。我希望能够从 QPushButton 拖放到 QTableView 的单元格中。我在网上看了一些教程,但似乎停留在第一步。下面的例子是从惊人的 zetcode 教程改变而来的:http: //zetcode.com/tutorials/pyqt4/dragdrop/
使用下面的代码,当我将按钮拖到 tableWidget 中时,dragEnterEvent 似乎被调用了,但是一旦我将鼠标悬停在表格上,我就会得到那个符号,我不允许将其放在表格上,所以永远不能参加 drop 事件:(
我不得不承认我对 pyqt 还很陌生,所以可能会遗漏一些非常简单的东西。非常感谢我能得到的任何帮助!干杯戴夫
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
class Button(QtGui.QPushButton):
def __init__(self, title, parent):
super(Button, self).__init__(title, parent)
def mouseMoveEvent(self, e):
if e.buttons() != QtCore.Qt.RightButton:
return
mimeData = QtCore.QMimeData()
drag = QtGui.QDrag(self)
drag.setMimeData(mimeData)
drag.setHotSpot(e.pos() - self.rect().topLeft())
dropAction = drag.start(QtCore.Qt.MoveAction)
def mousePressEvent(self, e):
QtGui.QPushButton.mousePressEvent(self, e)
if e.button() == QtCore.Qt.LeftButton:
print 'press'
class MyTable(QtGui.QTableWidget):
def __init__(self, rows, columns, parent):
super(MyTable, self).__init__(rows, columns, parent)
self.setAcceptDrops(True)
def dragEnterEvent(self, e):
print e.accept()
def dropEvent(self, e):
print 'blah'
position = e.pos()
self.button.move(position)
e.setDropAction(QtCore.Qt.MoveAction)
e.accept()
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.setAcceptDrops(True)
self.button = Button('Button', self)
self.table = MyTable(2,2,self)
self.table.setAcceptDrops(True)
self.table.setDragEnabled(True)
self.setWindowTitle('Click or Move')
self.setGeometry(300, 300, 280, 150)
layout = QtGui.QVBoxLayout()
layout.addWidget(self.button)
layout.addWidget(self.table)
self.setLayout(layout)
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
ex.show()
app.exec_()
if __name__ == '__main__':
main()