1 回答
TA贡献1785条经验 获得超4个赞
该问题不是由appendRow 方法引起的,而是由未记录的行为引起的。似乎在树类型模型中,除了没有子节点产生这种意外行为的节点之外,所有节点始终具有相同数量的列。解决方法是在文本项中创建带有 Qt::NoItemFlags 标志的 QStandardItem,以便用户无法与它们交互:
import sys
from PyQt5.QtCore import QRect, Qt
from PyQt5.QtGui import QStandardItemModel, QStandardItem
from PyQt5.QtWidgets import QApplication, QMainWindow, QTreeView, QWidget
class OrgItemModel(QStandardItemModel):
def __init__(self, parent=None):
super().__init__(parent)
self.setHorizontalHeaderLabels(["Tasks", "Due date", "Notes"])
def configure_from_list(model, lines):
def get_parent_item(depth):
parent = model.invisibleRootItem()
if depth == 0:
return parent
for _ in range(depth):
if parent.hasChildren():
parent = parent.child(parent.rowCount() - 1)
else:
it = QStandardItem()
it.setFlags(Qt.NoItemFlags)
parent.appendRow(it)
parent = it
return parent
for line in lines:
values = line.strip("=")
depth = (len(line) - len(values)) // 2
items = []
for value in values.split("|||"):
text = value.strip()
item = QStandardItem()
if text:
item.setText(text)
else:
item.setFlags(Qt.NoItemFlags)
items.append(item)
parent_item = get_parent_item(depth)
parent_item.appendRow(items)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.resize(1100, 580)
self.centralwidget = QWidget(MainWindow)
self.treeView = QTreeView(self.centralwidget)
self.treeView.setGeometry(QRect(20, 20, 1000, 320))
MainWindow.setCentralWidget(self.centralwidget)
class MyWindow(QMainWindow):
def __init__(self):
super(MyWindow, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
lines = [
"Europe ||| 2020-10-26 ||| some notes",
"==France ||| 2020-10-27 ||| some France notes",
"====Paris ||| --- ||| blah blah",
"==Germany ||| ||| ",
"==Italy ||| 2020-10-28 ||| some Italy notes",
"====Rome ||| ||| ",
"==Ireland ||| 2020-10-30 ||| blah blah",
]
model = OrgItemModel()
self.ui.treeView.setModel(model)
configure_from_list(model, lines)
self.ui.treeView.expandAll()
app = QApplication(sys.argv)
application = MyWindow()
application.show()
sys.exit(app.exec())
添加回答
举报