gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 02:53:23 26 4
gpt4 key购买 nike

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

这是目前的样子: enter image description here

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

enter image description here

我只需要更大尺寸的菜单栏。

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

最佳答案

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

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

或者(如果出于任何原因,该行为无法按预期工作或将来不再支持),您可以创建一个 QProxyStyle子类,实现它的 styleHint如果给定的提示是 SH_Menu_Scrollable,则返回 True

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())
# ...

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

更新

由于项目很多,出于各种原因,使用 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()

关于python - 如何使qtablewidget中过滤器中使用的菜单栏在pyqt5中可滚动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62246492/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com