也许我找错地方了,或者也许我不太完全理解这个概念;但我试图找到一个工作示例,在其中我可以将文本文件放在 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
关于python - 将项目放到 QComboBox 上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49100091/