[PyQt] Questions: QstandardItemModel and moveRow

Gottfried Müller gottfried.mueller at gmx.de
Tue Jul 30 08:17:09 BST 2019


Hi,

a bigger barrier for me again. I want to move one item in a 
QStandardItemModel. I have no idea why my example does not work. I want 
to move item "5" as a child of item "1" and at the end if the children. 
But nothing happens. Why? And can I find any messages about the reason. 
And how I can move an item "6" for example as a sibling of items "0" and 
"4". What is there the parent?

Gottfried

Here my example:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# pylint: disable=missing-docstring

import sys

from PyQt5.QtWidgets import QApplication, QWidget, QTreeView, 
QVBoxLayout, QPushButton
from PyQt5.QtGui import QStandardItemModel, QStandardItem


class ApplWindow(QWidget):

     def __init__(self, parent=None):
         super().__init__(parent)
         btn = QPushButton("Start move", parent=self)
         self.mdl = QStandardItemModel(parent=self)
         self.tree = QTreeView(parent=self)
         self.tree.setModel(self.mdl)
         self.tree.setHeaderHidden(True)
         layout = QVBoxLayout()
         layout.addWidget(btn)
         layout.addWidget(self.tree)
         self.setLayout(layout)
         self.items = [QStandardItem(str(idx)) for idx in range(7)]
         self.items[1].appendRow(self.items[2])
         self.items[1].appendRow(self.items[3])
         self.items[0].appendRow(self.items[1])
         self.mdl.appendRow(self.items[0])
         self.items[4].appendRow(self.items[5])
         self.items[4].appendRow(self.items[6])
         self.mdl.appendRow(self.items[4])
         self.tree.expandToDepth(1)
         btn.pressed.connect(self.startMove)

     def startMove(self):
         srcItem = self.items[5]
         dstParent = self.items[1]
         print('mv_01: item={} -> parent={}'.format(srcItem.text(), 
dstParent.text()))
         srcParentIdx = self.mdl.indexFromItem(srcItem.parent())
         dstParentIdx = self.mdl.indexFromItem(dstParent)
         print('idxValid_01:', srcParentIdx.isValid(), 
dstParentIdx.isValid())
         print('rows_01:', srcItem.row(), dstParent.rowCount())
         rc = self.mdl.moveRow(
             srcParentIdx, srcItem.row(), dstParentIdx, dstParent.rowCount()
         )
         print('rc_01:', rc)


def main():
     appl = QApplication(sys.argv)
     applWindow = ApplWindow()
     applWindow.show()
     return appl.exec_()


if __name__ == "__main__":
     main()



More information about the PyQt mailing list