Perhaps I am looking in the wrong place, or maybe I don't quite understand the concept fully; but I'm trying to find a working example where I can drop a text file on a QComboBox
, and it will trigger a drop event that I can handle. I looking through the documentation, but there isn't a whole lot of information on the subject.
I have also searched around, but I haven't really found anything either. If I'm just not looking in the right place, please feel free to point me in the right direction.
You have to overwrite the dragEnterEvent
method to enable what type of elements are accepted and the dropEvent
method where you will get information about the dragged element. But for this you must use self.setAcceptDrops(True)
to enable that behavior
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_())
If you need more information you can check the Qt documentation