如何使qtablewidget中过滤器中使用的菜单栏在pyqt5中可滚动?

How to make a menu bar used in filter in qtablewidget be scrollable in pyqt5?

我是 pyqt 的新手,这个问题可能很愚蠢。任何帮助,我将不胜感激。我有从这个页面获得的代码,它在过滤 qtable 小部件时进行编码。这段代码非常适合我想要的过滤输出。但是我有一个 table 并且它有很多行,我希望用于过滤的菜单栏是可滚动的,而不是在行中显示所有唯一的内容。我想要固定大小的菜单栏高度。

这是代码:

import csv
import sys
from PyQt5 import QtCore

from PyQt5 import QtGui, QtWidgets


class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent=parent)
        self.verticalLayout = QtWidgets.QVBoxLayout(self)
        self.table = QtWidgets.QTableWidget(self)
        self.table.setColumnCount(0)
        self.table.setRowCount(0)
        self.verticalLayout.addWidget(self.table)

        self.loadAll()
        self.horizontalHeader = self.table.horizontalHeader()
        self.horizontalHeader.sectionClicked.connect(self.on_view_horizontalHeader_sectionClicked)
        self.keywords = dict([(i, []) for i in range(self.table.columnCount())])
        self.checkBoxs = []
        self.col = None

    def slotSelect(self, state):

        for checkbox in self.checkBoxs:
            checkbox.setChecked(QtCore.Qt.Checked == state)

    def on_view_horizontalHeader_sectionClicked(self, index):
        self.menu = QtWidgets.QMenu()
        self.col = index

        data_unique = []
        self.checkBoxs = []

        checkBox = QtWidgets.QCheckBox("Select all", self.menu)
        checkableAction = QtWidgets.QWidgetAction(self.menu)
        checkableAction.setDefaultWidget(checkBox)
        self.menu.addAction(checkableAction)
        checkBox.setChecked(True)
        checkBox.stateChanged.connect(self.slotSelect)

        for i in range(self.table.rowCount()):
            if not self.table.isRowHidden(i):
                item = self.table.item(i, index)
                if item.text() not in data_unique:
                    data_unique.append(item.text())
                    checkBox = QtWidgets.QCheckBox(item.text(), self.menu)
                    checkBox.setChecked(True)
                    checkableAction = QtWidgets.QWidgetAction(self.menu)
                    checkableAction.setDefaultWidget(checkBox)
                    self.menu.addAction(checkableAction)
                    self.checkBoxs.append(checkBox)

        btn = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
                                     QtCore.Qt.Horizontal, self.menu)
        btn.accepted.connect(self.menuClose)
        btn.rejected.connect(self.menu.close)
        checkableAction = QtWidgets.QWidgetAction(self.menu)
        checkableAction.setDefaultWidget(btn)
        self.menu.addAction(checkableAction)

        headerPos = self.table.mapToGlobal(self.horizontalHeader.pos())

        posY = headerPos.y() + self.horizontalHeader.height()
        posX = headerPos.x() + self.horizontalHeader.sectionPosition(index)
        self.menu.exec_(QtCore.QPoint(posX, posY))


    def menuClose(self):
        self.keywords[self.col] = []
        for element in self.checkBoxs:
            if element.isChecked():
                self.keywords[self.col].append(element.text())
        self.filterdata()
        self.menu.close()

    def loadAll(self):
        with open("pokemon_data.csv", "r") as inpfil:
            reader = csv.reader(inpfil, delimiter=',')
            csheader = next(reader)
            ncol = len(csheader)
            data = list(reader)
            row_count = len(data)

            self.table.setRowCount(row_count)
            self.table.setColumnCount(ncol)
            self.table.setHorizontalHeaderLabels(('%s' % ', '.join(map(str, csheader))).split(","))

            for ii in range(0, row_count):
                mainins = data[ii]
                for var in range(0, ncol):
                    self.table.setItem(ii, var, QtWidgets.QTableWidgetItem(mainins[var]))

    def clearFilter(self):
        for i in range(self.table.rowCount()):
            self.table.setRowHidden(i, False)

    def filterdata(self):

        columnsShow = dict([(i, True) for i in range(self.table.rowCount())])

        for i in range(self.table.rowCount()):
            for j in range(self.table.columnCount()):
                item = self.table.item(i, j)
                if self.keywords[j]:
                    if item.text() not in self.keywords[j]:
                        columnsShow[i] = False
        for key, value in columnsShow.items():
            self.table.setRowHidden(key, not value)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

这是目前的样子:

当我尝试通过单击 header 进行过滤时,我的所有桌面 window 都被填满了,因为我的 table 中有太多行,如下图所示。

我只需要更大的菜单栏。

我尝试搜索与此相关的查询,但我找不到我可以将它集成到这段代码中。请温和地回应你,因为我对此很陌生。非常感谢!

最简单的解决方案是使用未记录的样式表 属性(如 this post 未接受的答案中所建议)。

    def on_view_horizontalHeader_sectionClicked(self, index):
        self.menu = QtWidgets.QMenu()
        self.menu.setStyleSheet('QMenu { menu-scrollable: true; }')
        # ...

或者(如果出于任何原因该行为无法按预期工作或将来不再支持该行为),您可以创建 QProxyStyle subclass, implement its styleHint 和 return True如果给定的提示是 SH_Menu_Scrollable.

class ProxyStyle(QtWidgets.QProxyStyle):
    def styleHint(self, hint, option, widget, data):
        if hint == self.SH_Menu_Scrollable:
            return True
        return super().styleHint(hint, option, widget, data)

# ...

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    app.setStyle(ProxyStyle())
    w = Widget()
    w.show()
    sys.exit(app.exec_())

如果您只想为该菜单保留该行为,您可以将代理样式应用于菜单而不是对整个应用程序执行此操作:

    def on_view_horizontalHeader_sectionClicked(self, index):
        self.menu = QtWidgets.QMenu()
        self.menu.setStyle(ProxyStyle())
        # ...

顺便说一下,您使用的是 menu,而不是 menubar。菜单栏是通常放置在 window 顶部的小部件,包含不同的项目,每个项目(可能)是一个菜单。

更新

由于项目很多,出于各种原因,使用 QMenu 并不是一个好的解决方案。 更好的方法是使用包含 QListWidget 和按钮框的 QWidget。为了保持与菜单类似的行为(如果在菜单外单击它应该关闭),您可以添加 Popup window 标志。

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        # ...
        self.dialog = QtWidgets.QWidget()
        self.dialog.setWindowFlags(
            self.dialog.windowFlags() | QtCore.Qt.Popup | QtCore.Qt.FramelessWindowHint)
        self.dialog.setMaximumHeight(300)
        layout = QtWidgets.QVBoxLayout(self.dialog)
        self.dialogList = QtWidgets.QListWidget()
        layout.addWidget(self.dialogList)
        self.dialogList.itemChanged.connect(self.slotSelect)

        buttonBox = QtWidgets.QDialogButtonBox(
           QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel)
        layout.addWidget(buttonBox)
        buttonBox.accepted.connect(self.menuClose)
        buttonBox.rejected.connect(self.dialog.hide)

    def on_view_horizontalHeader_sectionClicked(self, index):
        self.dialogList.clear()
        self.selectAllItem = QtWidgets.QListWidgetItem('Select all')
        self.selectAllItem.setCheckState(QtCore.Qt.Unchecked)
        self.dialogList.addItem(self.selectAllItem)

        self.col = index
        self.itemList = []
        data_unique = []
        for i in range(self.table.rowCount()):
            if not self.table.isRowHidden(i):
                item = self.table.item(i, index)
                if item == self.selectAllItem:
                    continue
                if item.text() not in data_unique:
                    item = QtWidgets.QListWidgetItem(item.text())
                    item.setCheckState(QtCore.Qt.Unchecked)
                    self.dialogList.addItem(item)
                    self.itemList.append(item)

        self.dialog.move(QtGui.QCursor.pos())
        self.dialog.show()

    def slotSelect(self, item):
        # temporally disconnect the signal to avoid recursion
        self.dialogList.itemChanged.disconnect(self.slotSelect)
        if item == self.selectAllItem:
            state = item.checkState()
            for i in self.itemList:
                i.setCheckState(state)
        else:
            states = [i.checkState() for i in self.itemList]
            if all(states):
                self.selectAllItem.setCheckState(QtCore.Qt.Checked)
            elif not any(states):
                self.selectAllItem.setCheckState(QtCore.Qt.Unchecked)
            else:
                self.selectAllItem.setCheckState(QtCore.Qt.PartiallyChecked)

        # reconnect the signal back again
        self.dialogList.itemChanged.connect(self.slotSelect)

    def menuClose(self):
        self.dialog.hide()
        self.keywords[self.col] = []
        for item in self.itemList:
            if item.checkState():
                self.keywords[self.col].append(item.text())
        self.filterdata()