在 QComboBox 上放置一个项目?
Dropping an item on a QComboBox?
也许我看错地方了,或者我没有完全理解这个概念;但我试图找到一个工作示例,我可以在其中将文本文件放在 QComboBox
上,它会触发我可以处理的放置事件。我查看了文档,但没有太多关于该主题的信息。
我也找了一圈,也没找到。如果我没有找到正确的地方,请随时为我指出正确的方向。
您必须重写 dragEnterEvent
方法以启用接受什么类型的元素,以及 dropEvent
方法,您将在其中获取有关拖动元素的信息。但是为此,您必须使用 self.setAcceptDrops(True)
来启用该行为
import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class ComboBox(QComboBox):
def __init__(self, *args, **kwargs):
QComboBox.__init__(self, *args, **kwargs)
self.setAcceptDrops(True)
def dragEnterEvent(self, event):
#print("formats: ", event.mimeData().formats())
if event.mimeData().hasFormat("text/plain"):
event.acceptProposedAction()
def dropEvent(self, event):
url = QUrl(event.mimeData().text().strip())
if url.isLocalFile():
file = QFile(url.toLocalFile())
if file.open(QFile.ReadOnly|QFile.Text):
ts = QTextStream(file)
while not ts.atEnd():
print(ts.readLine())
if __name__ == '__main__':
app = QApplication(sys.argv)
w = ComboBox()
w.addItems(["item {}".format(i) for i in range(10)])
w.show()
sys.exit(app.exec_())
如果您需要更多信息,可以查看 Qt documentation
也许我看错地方了,或者我没有完全理解这个概念;但我试图找到一个工作示例,我可以在其中将文本文件放在 QComboBox
上,它会触发我可以处理的放置事件。我查看了文档,但没有太多关于该主题的信息。
我也找了一圈,也没找到。如果我没有找到正确的地方,请随时为我指出正确的方向。
您必须重写 dragEnterEvent
方法以启用接受什么类型的元素,以及 dropEvent
方法,您将在其中获取有关拖动元素的信息。但是为此,您必须使用 self.setAcceptDrops(True)
来启用该行为
import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class ComboBox(QComboBox):
def __init__(self, *args, **kwargs):
QComboBox.__init__(self, *args, **kwargs)
self.setAcceptDrops(True)
def dragEnterEvent(self, event):
#print("formats: ", event.mimeData().formats())
if event.mimeData().hasFormat("text/plain"):
event.acceptProposedAction()
def dropEvent(self, event):
url = QUrl(event.mimeData().text().strip())
if url.isLocalFile():
file = QFile(url.toLocalFile())
if file.open(QFile.ReadOnly|QFile.Text):
ts = QTextStream(file)
while not ts.atEnd():
print(ts.readLine())
if __name__ == '__main__':
app = QApplication(sys.argv)
w = ComboBox()
w.addItems(["item {}".format(i) for i in range(10)])
w.show()
sys.exit(app.exec_())
如果您需要更多信息,可以查看 Qt documentation