qt - How to implement a tree-based QComboBox -
i came following class (treecombobox
) using two-part recipe @ developer.nokia.com (part 1, part 2):
from pyqt5.qtcore import * pyqt5.qtwidgets import * pyqt5.qtgui import * class treecombobox(qcombobox): def __init__(self, *args): super().__init__(*args) self.__skip_next_hide = false tree_view = qtreeview(self) tree_view.setframeshape(qframe.noframe) tree_view.setedittriggers(tree_view.noedittriggers) tree_view.setalternatingrowcolors(true) tree_view.setselectionbehavior(tree_view.selectrows) tree_view.setwordwrap(true) tree_view.setallcolumnsshowfocus(true) self.setview(tree_view) self.view().viewport().installeventfilter(self) def showpopup(self): self.setrootmodelindex(qmodelindex()) super().showpopup() def hidepopup(self): self.setrootmodelindex(self.view().currentindex().parent()) self.setcurrentindex(self.view().currentindex().row()) if self.__skip_next_hide: self.__skip_next_hide = false else: super().hidepopup() def selectindex(self, index): self.setrootmodelindex(index.parent()) self.setcurrentindex(index.row()) def eventfilter(self, object, event): if event.type() == qevent.mousebuttonpress , object self.view().viewport(): index = self.view().indexat(event.pos()) self.__skip_next_hide = not self.view().visualrect(index).contains(event.pos()) return false app = qapplication([]) combo = treecombobox() combo.resize(200, 30) parent_item = qstandarditem('item 1') parent_item.appendrow([qstandarditem('child'), qstandarditem('yesterday')]) model = qstandarditemmodel() model.appendrow([parent_item, qstandarditem('today')]) model.appendrow([qstandarditem('item 2'), qstandarditem('today')]) model.setheaderdata(0, qt.horizontal, 'name', qt.displayrole) model.setheaderdata(1, qt.horizontal, 'date', qt.displayrole) combo.setmodel(model) combo.show() app.exec_()
Comments
Post a Comment