Dropping an item on a QComboBox?

ぃ、小莉子 提交于 2019-12-11 11:45:42

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/49100091/dropping-an-item-on-a-qcombobox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!