在QHeaderView和QListWidget之间拖放列

时间:2017-11-14 17:21:56

标签: python qt drag-and-drop pyqt qheaderview

我在使用API Reviews拖动&掉落功能。当我继承QHeaderView时,我能够接受没有问题的丢弃。但是,当我点击QHeaderView并尝试从其中一列拖动时,似乎没有任何内容发生。

下面我重新实现了几个拖动事件,只要它们被调用就可以打印。但是,只有QHeaderView成功。没有其他事件如dragEnterEvent被调用。我的最终目标是拥有一个startDrag,我可以将列拖到QTableView(基本上隐藏列),然后用户可以将QListWidget项拖回QListWidget 1}}如果他们希望列及其数据再次可见。但是,在我理解为什么QTableView不允许我拖动之前,我无法前进。任何帮助将不胜感激。

QHeaderView

1 个答案:

答案 0 :(得分:1)

QHeaderView类不使用从QAbstractItemView继承的拖放方法,因为它永远不需要启动拖动操作。拖放仅用于重新排列列,并且没有必要使用QDrag机制。

鉴于此,有必要实现自定义拖放处理(使用mousePressEventmouseMoveEventdropEvent),还提供编码和解码mime数据的功能Qt用于在视图之间传递项目的格式。 table-widget需要一个事件过滤器,以便在隐藏所有列时仍然可以删除;以及列表小部件,阻止它将项目复制到自身。

下面的演示脚本实现了所有这些。可能需要更多的改进,但它应该足以让你开始:

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

class MyHeader(QHeaderView):
    MimeType = 'application/x-qabstractitemmodeldatalist'
    columnsChanged = pyqtSignal(int)

    def __init__(self, parent=None):
        super().__init__(Qt.Horizontal, parent)
        self.setDragEnabled(True)
        self.setAcceptDrops(True)
        self._dragstartpos = None

    def encodeMimeData(self, items):
        data = QByteArray()
        stream = QDataStream(data, QIODevice.WriteOnly)
        for column, label in items:
            stream.writeInt32(0)
            stream.writeInt32(column)
            stream.writeInt32(2)
            stream.writeInt32(int(Qt.DisplayRole))
            stream.writeQVariant(label)
            stream.writeInt32(int(Qt.UserRole))
            stream.writeQVariant(column)
        mimedata = QMimeData()
        mimedata.setData(MyHeader.MimeType, data)
        return mimedata

    def decodeMimeData(self, mimedata):
        data = []
        stream = QDataStream(mimedata.data(MyHeader.MimeType))
        while not stream.atEnd():
            row = stream.readInt32()
            column = stream.readInt32()
            item = {}
            for count in range(stream.readInt32()):
                key = stream.readInt32()
                item[key] = stream.readQVariant()
            data.append([item[Qt.UserRole], item[Qt.DisplayRole]])
        return data

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self._dragstartpos = event.pos()
        super().mousePressEvent(event)

    def mouseMoveEvent(self, event):
        if (event.buttons() & Qt.LeftButton and
            self._dragstartpos is not None and
            (event.pos() - self._dragstartpos).manhattanLength() >=
            QApplication.startDragDistance()):
            column = self.logicalIndexAt(self._dragstartpos)
            data = [column, self.model().headerData(column, Qt.Horizontal)]
            self._dragstartpos = None
            drag = QDrag(self)
            drag.setMimeData(self.encodeMimeData([data]))
            action = drag.exec(Qt.MoveAction)
            if action != Qt.IgnoreAction:
                self.setColumnHidden(column, True)

    def dropEvent(self, event):
        mimedata = event.mimeData()
        if mimedata.hasFormat(MyHeader.MimeType):
            if event.source() is not self:
                for column, label in self.decodeMimeData(mimedata):
                    self.setColumnHidden(column, False)
                event.setDropAction(Qt.MoveAction)
                event.accept()
            else:
                event.ignore()
        else:
            super().dropEvent(event)

    def setColumnHidden(self, column, hide=True):
        count = self.count()
        if 0 <= column < count and hide != self.isSectionHidden(column):
            if hide:
                self.hideSection(column)
            else:
                self.showSection(column)
            self.columnsChanged.emit(count - self.hiddenSectionCount())

class Form(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.listWidget = QListWidget()
        self.listWidget.setAcceptDrops(True)
        self.listWidget.setDragEnabled(True)
        self.listWidget.viewport().installEventFilter(self)

        self.tableWidget = QTableWidget()
        header = MyHeader(self)
        self.tableWidget.setHorizontalHeader(header)
        self.tableWidget.setRowCount(5)
        self.tableWidget.setColumnCount(4)

        labels = ["Column 1", "Column 2", "Column 3", "Column 4"]
        self.tableWidget.setHorizontalHeaderLabels(labels)
        for column, label in enumerate(labels):
            if column > 1:
                item = QListWidgetItem(label)
                item.setData(Qt.UserRole, column)
                self.listWidget.addItem(item)
                header.hideSection(column)

        header.columnsChanged.connect(
            lambda count: self.tableWidget.setAcceptDrops(not count))
        self.tableWidget.viewport().installEventFilter(self)

        splitter = QSplitter(Qt.Horizontal)
        splitter.addWidget(self.listWidget)
        splitter.addWidget(self.tableWidget)
        layout = QHBoxLayout()
        layout.addWidget(splitter)
        self.setLayout(layout)

    def eventFilter(self, source, event):
        if event.type() == QEvent.Drop:
            if source is self.tableWidget.viewport():
                self.tableWidget.horizontalHeader().dropEvent(event)
                return True
            else:
                event.setDropAction(Qt.MoveAction)
        return super().eventFilter(source, event)

if __name__=='__main__':

    app = QApplication(sys.argv)
    form = Form()
    form.setGeometry(600, 50, 600, 200)
    form.show()
    sys.exit(app.exec_())