如何在QStandardItem的图标上方显示文本?

时间:2019-04-23 00:30:40

标签: python python-2.7 pyside qtableview qstandarditemmodel

我正在尝试显示图标和文本的表格,以使每个项目在图标上方都有文本。

我目前正在使用QStandardItems和QStandardItemModel和QTableView来显示信息,但是文本仅显示在图标的右侧。我还没有找到更改文本显示位置的方法。我还尝试实现QAbstractTableModel并覆盖data方法以返回Qt.DecorationRole的图标和Qt.DisplayRole的文本,但是它也仅显示在图标的右侧。

例如:

<script>
    window.onload = function fn(){
    var x = document.getElementById("DescChange");
    var y = document.getElementById("CostChange");
    var a = document.getElementById("dropdown");

    a.addEventListener('change', function(){
        if (a.value == 0){
            x.innerHTML = "Description: Basic care for car including wax and buffer";
            y.innerHTML = "Total cost:" + 59.99;
        }
        else if (a.value == 1){
            x.innerHTML = "Mid-level care for car including Basic services and repainting";
            y.innerHTML = "Total cost:" + 119.99;
        }
        else if (a.value == 2){
            x.innerHTML = "Advanced care for car including Basic, Intermediate and interior + window repair";
            y.innerHTML = "Total cost:" + 299.99;
        }
        else{
            x.innerHTML = "";
            y.innerHTML = "";
        }

      });

    }
</script>

1 个答案:

答案 0 :(得分:0)

在这种情况下,您必须使用委托:

from PySide import QtCore, QtGui


class StyledItemDelegate(QtGui.QStyledItemDelegate):
    def initStyleOption(self, option, index):
        super(StyledItemDelegate, self).initStyleOption(option, index)
        option.decorationPosition = QtGui.QStyleOptionViewItem.Bottom
        option.displayAlignment = QtCore.Qt.AlignHCenter | QtCore.Qt.AlignTop


class CustomTableView(QtGui.QTableView):
    """Table view of icons and text."""

    def __init__(self):
        super(CustomTableView, self).__init__()
        delegate = StyledItemDelegate(self)
        self.setItemDelegate(delegate)
        self.verticalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents)
        custom_model = QtGui.QStandardItemModel()
        for v in range(10):
            for i in range(10):
                new_item = QtGui.QStandardItem(QtGui.QIcon("image.png"), str(i))
                custom_model.setItem(v, i, new_item)
        self.setModel(custom_model)


if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)
    w = CustomTableView()
    w.show()
    sys.exit(app.exec_())

enter image description here