I have a QTreeView
with a QStandardItemModel
and QStandardItems
. I want to add buttons that lead from one element to the next or to the previous element. Getting the index from the current element works, but how to get the index from the next one or the one before it? Below is an example of the code. The missing code parts are indicated.
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QTreeView, QPushButton, QVBoxLayout, QWidget
from PyQt5.Qt import QStandardItemModel, QStandardItem
class AppDemo(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('World Country Diagram')
self.resize(500, 700)
self.treeView = QTreeView()
self.treeView.setHeaderHidden(True)
treeModel = QStandardItemModel()
self.rootNode = treeModel.invisibleRootItem()
# America
america = QStandardItem('America')
california = QStandardItem('California')
america.appendRow(california)
oakland = QStandardItem('Oakland')
sanfrancisco = QStandardItem('San Francisco')
sanjose = QStandardItem('San Jose')
california.appendRow(oakland)
california.appendRow(sanfrancisco)
california.appendRow(sanjose)
texas = QStandardItem('Texas')
america.appendRow(texas)
austin = QStandardItem('Austin')
houston = QStandardItem('Houston')
dallas = QStandardItem('dallas')
texas.appendRow(austin)
texas.appendRow(houston)
texas.appendRow(dallas)
# Canada
canada = QStandardItem('Canada')
alberta = QStandardItem('Alberta')
bc = QStandardItem('British Columbia')
ontario = QStandardItem('Ontario')
canada.appendRows([alberta, bc, ontario])
self.rootNode.appendRow(america)
self.rootNode.appendRow(canada)
self.treeView.setModel(treeModel)
self.treeView.expandAll()
self.treeView.selectionModel().selectionChanged.connect(self.display)
self.button_next = QPushButton("Next", self)
self.button_next.clicked.connect(self.next)
self.button_before = QPushButton("Before", self)
self.button_before.clicked.connect(self.next)
layout = QVBoxLayout()
layout.addWidget(self.button_next)
layout.addWidget(self.button_before)
layout.addWidget(self.treeView)
window = QWidget()
window.setLayout(layout)
self.setCentralWidget(window)
def display(self, ItemSelection):
selection_model = self.treeView.selectionModel()
index = selection_model.currentIndex()
print(self.treeView.model().itemData(index))
def next(self):
selection_model = self.treeView.selectionModel()
modelIndex = selection_model.currentIndex()
# code missing
self.treeView.setCurrentIndex(modelIndex)
def before(self):
selection_model = self.treeView.selectionModel()
modelIndex = selection_model.currentIndex()
#code missing
self.treeView.setCurrentIndex(modelIndex)
app = QApplication(sys.argv)
demo = AppDemo()
demo.show()
sys.exit(app.exec_())