[英]identify an instance in drag-and-drop
我努力理解如何在拖放中識別類的實例,但我需要一些幫助。
下面我添加了一個來自“ http://zetcode.com/gui/pyqt5/dragdrop/ ”的示例來解釋。
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
ZetCode PyQt5 tutorial
In this program, we can press on a button with a left mouse
click or drag and drop the button with the right mouse click.
Author: Jan Bodnar
Website: zetcode.com
Last edited: August 2017
"""
from PyQt5.QtWidgets import QPushButton, QWidget, QApplication
from PyQt5.QtCore import Qt, QMimeData
from PyQt5.QtGui import QDrag
import sys
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)
drag.setHotSpot(e.pos() - self.rect().topLeft())
dropAction = drag.exec_(Qt.MoveAction)
def mousePressEvent(self, e):
super().mousePressEvent(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()
self.button.move(position)
e.setDropAction(Qt.MoveAction)
e.accept()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
ex.show()
app.exec_()
這是我的問題:
如果我實例化第二個按鈕
self.button2 = Button('Button2', self)
self.button2.move(100, 165)
我也可以移動 button2,但在 DropEvent 中,第一個按鈕“button”被移動。
如何在 DropEvent 中識別我移動“button2”和放置 button2?
所以:問題是:如何識別,它是哪個按鈕。 (我只找到了拖放示例,如何用另一個相同類型的元素替換標簽或按鈕)
還有一個問題:使用這種類型的代碼創建一個新實例。 如果我在 QT5 設計器中創建按鈕,則不可能在此代碼中將它們作為此類 Button 類的實例。 因此,在 QT5 設計器中定義拖放,將列表中的項目的拖放拖放到另一個列表中有效,但我無法識別,我拖動了哪個元素
如果您從中拖動的對象是 QWidget,那么您可以通過 QDropEvent source() 方法獲取它,而 QPushButton 是一個 QWidget,因此它在這種情況下有效:
def dropEvent(self, e):
if e.source() is not None:
position = e.pos()
e.source().move(position)
e.setDropAction(Qt.MoveAction)
e.accept()
請記住驗證它不是 None 因為源可能是另一個不是 QWidget 的窗口,所以你會得到一個異常
如果您希望通過 Qt Designer 添加的按鈕具有相同的功能,那么最簡單的解決方案是提升按鈕,SO 中有許多示例展示了如何操作:
你總是在 drop 事件中使用self.button
,所以它指的是同一個按鈕。 相反,您可以使用QDropEvent.source()
來獲取正確的小部件。
def dropEvent(self, e):
position = e.pos()
e.source().move(position) # source widget
e.setDropAction(Qt.MoveAction)
e.accept()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.