如何使用pyqt4在树视图中搜索项目名称

How to search a item name in tree view using with pyqt4

这是我的示例程序,我想在树视图中搜索一个项目,当我单击一个搜索按钮时,我只想在滚动区域显示该项目,我不知道 it.But 我尝试使用模型并设置排序方法,但它不能 work.can 任何人请帮助我如何在树中搜索项目 view.give 我任何例子。提前谢谢你。

下面是我的代码:

from PyQt4 import QtCore, QtGui

class InventoryDelegate(QtGui.QStyledItemDelegate):
    def paint(self, painter, option, index):
        super(InventoryDelegate, self).paint(painter, option, index)
        if not index.parent().isValid():
            painter.save()
            painter.setPen(QtGui.QPen(QtGui.QColor("white")))
            r = QtCore.QRect(option.rect)
            r.adjust(0, 1, 0, -1)
            painter.drawLine(r.topLeft(), r.topRight())
            painter.drawLine(r.bottomLeft(), r.bottomRight())
            painter.restore()

    def sizeHint(self, option, index):
        s = super(InventoryDelegate, self).sizeHint(option, index)
        s.setHeight(55)
        return s

class Inventory_Items(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(Inventory_Items, self).__init__(parent)
        inv_obj =[{u'productPrice': 123.0, u'productSerialId': u'123458', u'productName': u'Renewal Application Form', u'productDiscount': 0, u'productdp': u'/media/ecommerce/pictureUploads/1546958016_35_admin_index.jpeg', u'productUnit': u'Quantity', u'data': [{u'product': 1837, u'product__unit': u'Quantity', u'productVariant__unitPerpack': None, u'productVariant': None, u'productVariant__price': None, u'product__serialNo': u'123457', u'product__howMuch': 2.0, u'productVariant__serialId': None, u'product__price': 123.0, u'pk': 65, u'productVariant__sku': None, u'quantity': -11.0}, {u'product': 1837, u'product__unit': u'Quantity', u'productVariant__unitPerpack': None, u'productVariant': None, u'productVariant__price': None, u'product__serialNo': u'123458', u'product__howMuch': 2.0, u'productVariant__serialId': None, u'product__price': 123.0, u'pk': 67, u'productVariant__sku': None, u'quantity': 10.0}, {u'product': 1837, u'product__unit': u'Quantity', u'productVariant__unitPerpack': None, u'productVariant': None, u'productVariant__price': None, u'product__serialNo': u'123459', u'product__howMuch': 2.0, u'productVariant__serialId': None, u'product__price': 123.0, u'pk': 69, u'productVariant__sku': None, u'quantity': 30.0}], u'productPk': 1837}, {u'productPrice': 1760.0, u'productSerialId': u'1168', u'productName': u'Truth or Delusion', u'productDiscount': 5, u'productdp': u'/media/ecommerce/pictureUploads/1546959987_35_admin_default.png', u'productUnit': u'Kilogram', u'data': [{u'product': 2180, u'product__unit': u'Kilogram', u'productVariant__unitPerpack': None, u'productVariant': None, u'productVariant__price': None, u'product__serialNo': u'IND-BOK-D-2016-TRUDEL-02', u'product__howMuch': 1.0, u'productVariant__serialId': None, u'product__price': 1760.0, u'pk': 70, u'productVariant__sku': None, u'quantity': 10.0}, {u'product': 2180, u'product__unit': u'Kilogram', u'productVariant__unitPerpack': None, u'productVariant': None, u'productVariant__price': None, u'product__serialNo': u'IND-BOK-D-2016-TRUDEL-01', u'product__howMuch': 1.0, u'productVariant__serialId': None, u'product__price': 1760.0, u'pk': 71, u'productVariant__sku': None, u'quantity': 1.0}], u'productPk': 2180}, {u'productPrice': 240.0, u'productSerialId': u'1219', u'productName': u'One-to-One Follow Up Slips ( Qty 10 pads - 50 sheets per pad)', u'productDiscount': 0, u'productdp': u'/media/ecommerce/pictureUploads/https%3A//bnistore.in/wp-content/uploads/2016/02/323.jpg', u'productUnit': u'Quantity', u'data': [{u'product': 2185, u'product__unit': u'Quantity', u'productVariant__unitPerpack': None, u'productVariant': None, u'productVariant__price': None, u'product__serialNo': u'123457', u'product__howMuch': 1.0, u'productVariant__serialId': None, u'product__price': 240.0, u'pk': 62, u'productVariant__sku': None, u'quantity': -48.0}], u'productPk': 2185}, {u'productPrice': 1500.0, u'productSerialId': u'3293', u'productName': u'Membership Application Form (Package of 10)', u'productDiscount': 0, u'productdp': u'/media/ecommerce/pictureUploads/https%3A//bnistore.in/wp-content/uploads/2017/08/New-Members-Application-Form.png', u'productUnit': u'quantity', u'data': [{u'product': 2225, u'product__unit': u'quantity', u'productVariant__unitPerpack': None, u'productVariant': None, u'productVariant__price': None, u'product__serialNo': u'IND-PRT-D-2016-NEWAPP-1', u'product__howMuch': 1.0, u'productVariant__serialId': None, u'product__price': 1500.0, u'pk': 66, u'productVariant__sku': None, u'quantity': 81.0}], u'productPk': 2225}]
        w = QtGui.QWidget()
        vbox = QtGui.QVBoxLayout(w)
        hbox = QtGui.QHBoxLayout()
        self.le = QtGui.QLineEdit()
        search = QtGui.QPushButton("search")
        search.clicked.connect(self.search_item)
        hbox.addWidget(self.le)
        hbox.addWidget(search)
        vbox.addLayout(hbox)
        self.inventory_widget = QtGui.QTreeWidget(columnCount=7,
            expandsOnDoubleClick=False,
            indentation=0,
            focusPolicy=QtCore.Qt.NoFocus,
            iconSize=QtCore.QSize(40,60))
        vbox.addWidget(self.inventory_widget)
        self.inventory_widget.setColumnWidth(2, 350)
        self.inventory_widget.setStyleSheet("QWidget {background-color: black;color: white;}")
        header = self.inventory_widget.header()
        header.hide()
        header.setResizeMode(0, QtGui.QHeaderView.ResizeToContents)
        header.setResizeMode(1, QtGui.QHeaderView.ResizeToContents)
        header.setResizeMode(2, QtGui.QHeaderView.Stretch)
        header.setResizeMode(3, QtGui.QHeaderView.Stretch)
        header.setResizeMode(4, QtGui.QHeaderView.Stretch)
        header.setResizeMode(5, QtGui.QHeaderView.ResizeToContents)
        header.setResizeMode(6, QtGui.QHeaderView.ResizeToContents)

        delegate = InventoryDelegate(self.inventory_widget)
        self.inventory_widget.setItemDelegate(delegate)
        c=[]
        for obj in inv_obj:
            it = QtGui.QTreeWidgetItem()
            self.inventory_widget.addTopLevelItem(it)
            values = [
                obj["productName"],
                "Unit :  {0} ".format(obj["productUnit"]),
                "Price : {0} ".format(obj["productPrice"]),
                "Discount : {0} ".format(obj["productDiscount"])
            ]
            for i, t in enumerate(values):
                it.setText(i + 1, t)

            for v in obj['data']:
                child_it = QtGui.QTreeWidgetItem()
                it.addChild(child_it)
                value = [
                    v['product__serialNo'],
                    "{}".format(v['product__howMuch']),
                    "{}".format(v['quantity']),
                ]
                for l, m in enumerate(value):
                    child_it.setText(l + 1, m)
        self.inventory_widget.expandAll()
        self.setCentralWidget(w)

    def search_item(self):
        print self.le.text()
        #how to do search with item name(i.e like renewal)in tree view

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    settingobj= Inventory_Items()
    settingobj.showFullScreen()

    sys.exit(app.exec_())

图片:

您必须遍历具有特征名称的项目并在必要时隐藏,如果所有子项都隐藏了父项。

def search_item(self):
    filter_text = self.le.text()
    is_valid_filter = filter_text == ""
    for i in range(self.inventory_widget.topLevelItemCount()):
        top_item = self.inventory_widget.topLevelItem(i)
        flag = (str(filter_text).lower() in str(top_item.text(1)).lower())  or is_valid_filter
        top_item.setHidden(not flag)