import sys
import traceback
import os
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

class Main(QListWidget):
    """自定义的列表框：支持文件拖拽"""
    def __init__(self, parent=None):
        try:
            super(Main, self).__init__(parent)
            self.setAcceptDrops(True)
            self.file_list = []  # 文件列表
        except:
            traceback.print_exc()

    def dragEnterEvent(self, event):
        try:
            if event.mimeData().hasUrls:
                event.accept()
            else:
                event.ignore()
        except:
            traceback.print_exc()

    def dragMoveEvent(self, event):
        pass

    def dropEvent(self, event):
        try:
            urls = event.mimeData().urls()
            for each in urls:
                current = each.toLocalFile()
                if os.path.isfile(current) and current not in self.file_list:
                    self.file_list.append(current)
                    self.addItem(current)
        except:
            traceback.print_exc()

class Main(QDialog):
    """拖拽文件Demo"""
    def __init__(self, parent=None):
        try:
            super(Main, self).__init__(parent)
            self.init_ui()
        except:
            traceback.print_exc()

    def init_ui(self):
        try:
            self.setWindowTitle("拖入文件demo")
            self.resize(320, 480)

            self.listWidget = ListWidget(self)

            layout = QHBoxLayout()
            layout.addWidget(self.listWidget)
            self.setLayout(layout)
        except:
            traceback.print_exc()

if __name__ == '__main__':
    authorization = None
    app = QApplication(sys.argv)
    main = Main()
    main.show()
    sys.exit(app.exec_())
