我如何使用pyqt4将我的孩子小部件添加到树小部件中

时间:2019-02-20 12:42:02

标签: python-2.7 pyqt4

在我的程序中,我想将子项添加到产品项中,但是我对树形小部件一无所知,我尝试过类似的操作。我想为主要product_item添加序列号,单位数量和数量。在这里,我得到了需要显示子小部件的主要产品,例如下面的示例图像。请任何人指导我。

以下是我的代码:

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}]

        self.inventory_widget = QtGui.QTreeWidget(columnCount=7,
            expandsOnDoubleClick=False,
            indentation=0,
            focusPolicy=QtCore.Qt.NoFocus,
            iconSize=QtCore.QSize(40,60))

        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 i in inv_obj:
            for j in i['data']:
                print j['product__serialNo'],j['product__howMuch'],j['quantity'],"------" #for each product_item i have a  child data so this data i need to add  like as in  given image 
            it = QtGui.QTreeWidgetItem()
            self.inventory_widget.addTopLevelItem(it)
            k=list(["{0} ".format(i["productName"])] + ["Unit :  {0} ".format(i["productUnit"])]+["Price : {0} ".format(i["productPrice"])]+["Discount : {0} ".format(i["productDiscount"])])
            for i, t in enumerate([i["productName"]] + ["Unit :  {0} ".format(i["productUnit"])]+["Price : {0} ".format(i["productPrice"])]+["Discount : {0} ".format(i["productDiscount"])]):
                it.setText(i+1, t)





        self.inventory_widget.expandAll()
        self.setCentralWidget(self.inventory_widget)

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

    sys.exit(app.exec_())

enter image description here

1 个答案:

答案 0 :(得分:1)

您必须创建子项并使用addChild()添加:

# ...
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)
        widget = QtGui.QWidget(self)
        widget.setContentsMargins(0, 0, 0, 0)
        button_save = QtGui.QPushButton("add")
        button_save.setStyleSheet("background-color: blue;color: white;")
        button_delete = QtGui.QPushButton("delete")
        button_delete.setStyleSheet("background-color: red;color: white;")
        lay = QtGui.QHBoxLayout(widget)
        lay.setSpacing(0)
        lay.setContentsMargins(0, 0, 0, 0)
        lay.addWidget(button_save)
        lay.addWidget(button_delete)
        self.inventory_widget.setItemWidget(child_it, 4, widget)
self.inventory_widget.expandAll()
self.setCentralWidget(self.inventory_widget)
# ...