gpt4 book ai didi

python - TableView 中的行数意外影响交替行颜色

转载 作者:行者123 更新时间:2023-12-01 07:15:42 26 4
gpt4 key购买 nike

我有一个带有 TableView 的 PySide2 Qt 5.13.1 应用程序。根据表中的行数,我遇到了一些奇怪的行为。我正在尝试交替行颜色。当行数为偶数时,剥离将按预期进行。当行数为奇数时,我的 TableView 会出现棋盘图案,这是意外的。下面的两个屏幕截图之间的唯一区别是模型中的行数。

enter image description here

enter image description here

main.py

import sys

from PySide2.QtCore import QUrl
from PySide2.QtQml import QQmlApplicationEngine, qmlRegisterType
from PySide2.QtWidgets import QApplication

from table_model import TableModel

import qml_rc # noqa: F401


if __name__ == "__main__":
app = QApplication(sys.argv)

engine = QQmlApplicationEngine()

qmlRegisterType(TableModel, "TableModel", 1, 0, "TableModel")

engine.load(QUrl("qrc:/main.qml"))

if not engine.rootObjects():
sys.exit(-1)

sys.exit(app.exec_())

main.qml

import QtQuick 2.13
import QtQuick.Controls 2.13

import TableModel 1.0

ApplicationWindow {
visible: true

Component.onCompleted: {
showMaximized()
}

width: 640
height: 480

TableView {
id: tableView
clip: true
anchors.fill: parent
model: TableModel {}
topMargin: columnsHeader.implicitHeight

columnWidthProvider: function (column) {
return tableView.model ? tableView.width / tableView.model.columnCount() : 0
}

onWidthChanged: tableView.forceLayout()

delegate: Rectangle {
implicitWidth: tableView.columnWidthProvider(column)
implicitHeight: 40
color: index % 2 == 0 ? "grey" : "lightgrey"

Text {
text: display
}
}

Row {
id: columnsHeader
y: tableView.contentY
z: 2

Repeater {
model: tableView.columns > 0 ? tableView.columns : 1

Rectangle {
width: tableView.columnWidthProvider(modelData)
height: 60
clip: true

Label {
id: headerText
width: parent.width
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
text: tableView.model.headerData(modelData, Qt.Horizontal)
elide: Text.ElideRight
clip: true
}
}
}
}
}
}

表模型.py

from typing import Any, Optional

from PySide2.QtCore import QAbstractTableModel, QModelIndex, QObject, Qt

from table import Table


class TableModel(QAbstractTableModel):
def __init__(self, parent: QObject = None) -> None:
super().__init__(parent)
self._model_data = Table(
["This", "Is", "A", "Test", "Of", "Headers"],
[
["A", 1, 2, "B", "C", "D"],
["E", 3, 4, "F", "G", "H"],
["I", 5, 6, "J", "K", "L"],
["M", 7, 8, "N", "O", "P"],
["A", 1, 2, "B", "C", "D"],
["E", 3, 4, "F", "G", "H"],
["I", 5, 6, "J", "K", "L"],
["M", 7, 8, "N", "O", "P"],
["A", 1, 2, "B", "C", "D"],
["E", 3, 4, "F", "G", "H"],
["I", 5, 6, "J", "K", "L"],
# ["I", 5, 6, "J", "K", "L"],
])

def rowCount(self, parent=QModelIndex()) -> int:
return len(self._model_data.rows)

def columnCount(self, parent=QModelIndex()) -> int:
return len(self._model_data.headers)

def data(self, index: QModelIndex, role=Qt.DisplayRole) -> Optional[Any]:
if role != Qt.DisplayRole:
return None

if not self.checkIndex(index, QAbstractTableModel.CheckIndexOption.IndexIsValid):
return None

return self._model_data.rows[index.row()][index.column()]

def headerData(self, section: int, orientation, role) -> Optional[str]:
if role != Qt.DisplayRole:
return None

if section < 0 or section >= len(self._model_data.headers):
return None

return self._model_data.headers[section]

def reset_with_data(self, model_data: Table) -> None:
self.beginResetModel()
self._model_data = model_data
self.endResetModel()

表.py


from dataclasses import dataclass
from typing import Any, List


@dataclass
class Table:
headers: List[str]
rows: List[List[Any]]

qml.qrc

<RCC>
<qresource prefix="/">
<file>main.qml</file>
</qresource>
</RCC>

运行:

pipenv run pyside2-rcc -o qml_rc.py qml.qrc
pipenv run python main.py

最佳答案

index 属性并不代表行号,而是:

index = row + column * total_number_of_rows

而是使用row(或model.row)属性:

color: <b>model.row</b> % 2 == 0 ? "grey" : "lightgrey"

关于python - TableView 中的行数意外影响交替行颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57981505/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com