如何将复选框连接到QComboBox



当选中某些复选框时,我想过滤PyQt5 QCombox中的项目。

示例:

samplelist=["a1","a2","a3","b1","b2","b3"]是QComboxcomboBox的项目列表,并且我有两个复选框checkBoxacheckBoxb。如果

  • checkboxa已选中,checkboxb未选中:comboBox具有项["a1", "a2", "a3"]
  • 未选中checkboxa,选中checkboxbcomboBox具有["b1", "b2", "b3"]
  • checkboxa未勾选,checkboxb未勾选:comboBox为空
  • 检查checkboxa,检查checkboxbcomboBoxsamplelist

有人知道我如何将checkboxacheckbox连接到comboBox以实现所描述的结果吗?

最小示例(复选框未连接到组合框(

from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *  
class ExampleWindow(QDialog):
def __init__(self,parent=None):
super(ExampleWindow,self).__init__(parent)
mainLayout=QtWidgets.QGridLayout()

samplelist=["a1","a2","a3","b1","b2","b3"]
# Create combobox and add items.
self.comboBox = QComboBox()
self.comboBox.addItems(samplelist)
#Create checkboxes
self.checkBoxa = QCheckBox("Select a") 
self.checkBoxb = QCheckBox("Select b")

mainLayout.addWidget(self.comboBox,1,0,1,2)
mainLayout.addWidget(self.checkBoxa,0,0,1,1)
mainLayout.addWidget(self.checkBoxb,0,1,1,1)

self.setLayout(mainLayout)
if __name__ == "__main__":
app = QApplication(sys.argv)
mainWin = ExampleWindow()
mainWin.show()
sys.exit( app.exec_() )

由于您的问题不明确,我将假设每个QCheckBox都与一个字母相关联,并且您只想显示以与选中的QCheckBox关联的字母开头的项目。如果是这样,那么最好基于项目创建一个模型,并使用QSortFilterProxyModel对其进行筛选。

class FilterProxyModel(QSortFilterProxyModel):
def __init__(self, parent=None):
super().__init__(parent)
self._letters = list()
@property
def letters(self):
return self._letters
@letters.setter
def letters(self, letters):
self._letters = letters.copy()
self.invalidateFilter()
def filterAcceptsRow(self, source_row, source_parent):
index = self.sourceModel().index(source_row, 0, source_parent)
data = index.data()
return any(data.startswith(letter) for letter in self.letters)

class ExampleWindow(QDialog):
def __init__(self, parent=None):
super(ExampleWindow, self).__init__(parent)
mainLayout = QGridLayout(self)
letters = ("a", "b", "c", "d")
samplelist = [f"{letter}{i}" for i in range(1, 5) for letter in letters]
self.model = QStandardItemModel()
for e in samplelist:
item = QStandardItem(e)
self.model.appendRow(item)
self.proxy_model = FilterProxyModel()
self.proxy_model.setSourceModel(self.model)
self.comboBox = QComboBox()
self.comboBox.setModel(self.proxy_model)
self.checkboxs = []
for i, letter in enumerate(letters):
checkbox = QCheckBox(f"Select {letter}")
checkbox.setProperty("letter", letter)
checkbox.toggled.connect(self.handle_toggled)
mainLayout.addWidget(checkbox, 0, i)
self.checkboxs.append(checkbox)
mainLayout.addWidget(self.comboBox, 1, 0, 1, len(letters))
self.handle_toggled()
def handle_toggled(self):
letters = []
for checkbox in self.checkboxs:
if checkbox.isChecked():
letters.append(checkbox.property("letter"))
self.proxy_model.letters = letters

相关内容

  • 没有找到相关文章

最新更新