2

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

这是代码:

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_())

这是目前的样子: 在此处输入图像描述

当我尝试通过单击标题进行过滤时,我的所有桌面窗口都已填满,因为我的表格中有很多行,如下图所示。

在此处输入图像描述

我只需要更好的菜单栏大小。

我尝试搜索与此相关的查询,但我找不到可以将其集成到此代码中。请对您的回复保持温和,因为我对此真的很陌生。非常感谢!

4

1 回答 1

3

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

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

或者(如果出于任何原因,该行为无法按预期工作或将来删除它的支持)您可以创建一个QProxyStyle子类,实现它styleHintTrue在给定提示为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。菜单栏是通常放置在窗口顶部的小部件,包含不同的项目,每个项目(可能)是一个菜单。

更新

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

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()
于 2020-06-07T14:26:29.167 回答