I try my best to drag it to work. I want to be able to drag and drop from a QPushButton to a QTableView cell. I looked through several tutorials online, but it seems to be stuck in the first step. The following example is modified from the amazing zetcode tutorial:
http://zetcode.com/tutorials/pyqt4/dragdrop/
Using the code below, when I drag a button into a tableWidget, dragEnterEvent seems to be called, but as soon as I hover over the table, I get this character that Iām not allowed to throw at the table, so it can never get into the drop event: (
I have to admit that I'm pretty new to pyqt, so something very simple might be missing. It would be very helpful to get any help I could get! cheers dave
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()
source
share