最近学习PyQt5,我试图拖动QPushButton学习本教程Drag & drop a button widget,并做了一些改进,使按钮更准确,所以我添加
mime = e.mimeData().text()
x, y = mime.split(',')
根据@Avaris对此question,但我发现e.mimeData().text()
没有返回任何应该是光标相对于按钮的本地位置的坐标,我试图print(mime)
,并且得到一个没有任何内容的空白行,然后我print(mime.split(','))
得到['']
。
这里是代码:
import sys
from PyQt5.QtWidgets import QPushButton, QWidget, QApplication, QLabel
from PyQt5.QtCore import Qt, QMimeData
from PyQt5.QtGui import QDrag
from PyQt5 import QtCore
class Button(QPushButton):
def __init__(self, title, parent):
super().__init__(title, parent)
def mouseMoveEvent(self, e):
if e.buttons() != Qt.RightButton:
return
mimeData = QMimeData()
drag = QDrag(self)
drag.setMimeData(mimeData)
dropAction = drag.exec_(Qt.MoveAction)
def mousePressEvent(self, e):
QPushButton.mousePressEvent(self, e)
if e.button() == Qt.LeftButton:
print('press')
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setAcceptDrops(True)
self.button = Button('Button', self)
self.button.move(100, 65)
self.setWindowTitle('Click or Move')
self.setGeometry(300, 300, 280, 150)
def dragEnterEvent(self, e):
e.accept()
def dropEvent(self, e):
position = e.pos()
mime = e.mimeData().text()
x, y = mime.split(',')
#print(mime.split(','))
self.button.move(position - QtCore.QPoint(int(x), int(y)))
e.setDropAction(Qt.MoveAction)
e.accept()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
ex.show()
app.exec_()
答案 0 :(得分:2)
在answer of @Avaris中,您会注意到他们使用mouseMoveEvent
中的按钮位置设置了mimedata:
mimeData = QtCore.QMimeData()
# simple string with 'x,y'
mimeData.setText('%d,%d' % (e.x(), e.y()))
默认情况下,mimedata不包含任何内容。你必须自己设置一切!查看QMimeData
的文档,了解您还可以做什么(除了设置任意文本)