【问题标题】:Python / PyQt4: How to make a QComboBox Item draggablePython / PyQt4:如何使 QComboBox 项可拖动
【发布时间】:2014-01-17 20:10:11
【问题描述】:

我只是为了好玩而修补 PyQt...

到目前为止,我有以下代码,它接受从文本字段中删除来填充 QComboBox:

class ComboBox(QtGui.QComboBox):
def __init__(self, parent):
    super(ComboBox, self).__init__(parent)

    self.setAcceptDrops(True)

def dragEnterEvent(self, e):
    if e.mimeData().hasFormat('text/plain'):
        e.accept()
    else:
        e.ignore()

def dropEvent(self, e):

    self.addItem(QtCore.QString(e.mimeData().text()))

我现在想让 QComboBox 中的项目可拖动(就像您可以使用以下方法使用 QLineEdit 一样:

.setDragEnabled(True) 

有人知道我该怎么做吗?

非常感谢

P

【问题讨论】:

    标签: python qt python-2.7 pyqt4


    【解决方案1】:

    您可以使用combobox.view().setDragDropMode(Qt.QAbstractItemView.DragOnly) 启用拖动。以下工作示例说明了如何实现将项目从一个组合框拖动到另一个组合框:

    combobox = Qt.QComboBox()
    combobox.addItems(["test1", "test2", "test3"])
    combobox.show()
    combobox.view().setDragDropMode(Qt.QAbstractItemView.DragOnly)
    
    model_mime_type = 'application/x-qabstractitemmodeldatalist'
    
    class ComboBox(Qt.QComboBox):
      def __init__(self):
        super(ComboBox, self).__init__()
        self.setAcceptDrops(True)
    
      def dragEnterEvent(self, e):
        if e.mimeData().hasFormat(model_mime_type) or \
           e.mimeData().hasFormat('text/plain'):
          e.accept()
        else:
          e.ignore()
    
      def dropEvent(self, e):
        if e.mimeData().hasFormat(model_mime_type):
          encoded = e.mimeData().data(model_mime_type)
          stream = Qt.QDataStream(encoded, Qt.QIODevice.ReadOnly)
          while not stream.atEnd():
            row = stream.readInt()
            column = stream.readInt()
            map = stream.readQVariantMap()
            if len(map.values()) == 1:
              self.addItem(map.values()[0].toString())     
          combobox.hidePopup()   
        else:
          self.addItem(Qt.QString(e.mimeData().text()))
    
    c2 = ComboBox()
    c2.show()
    

    【讨论】:

    • 谢谢,太好了!如果我有足够的积分,我会投票!
    猜你喜欢
    • 2012-10-19
    • 2011-11-20
    • 1970-01-01
    • 2011-10-31
    • 1970-01-01
    • 1970-01-01
    • 2012-01-18
    • 2012-01-11
    • 2012-02-12
    相关资源
    最近更新 更多