salomonderossi
salomonderossi

Reputation: 2188

Change index of QStackedWidget in pyqt

I have a QListWidget and a QStackedWidget. The QListWidget shows the name of the Widget in the QStackedWidget. In the QListWidget you can rearrange the order of the Widgets via drag and drop.

So my question is, how can I update the changed order in the QStackedWidget?

Here is a minimal example to show the problem:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
from PyQt4 import QtGui, QtCore

class TestWidget(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.layout    = QtGui.QHBoxLayout(self)
        self.stack     = QtGui.QStackedWidget(self)
        self.item_list = QtGui.QListWidget(self)
        self.item_list.setDragEnabled(True)
        self.item_list.setDragDropMode(QtGui.QAbstractItemView.InternalMove)

        self.layout.addWidget(self.item_list)
        self.layout.addWidget(self.stack)

        for i in range(10):
            b_name = "Button %04i" % i
            i_name = "Item   %04i" % i
            self.stack.addWidget(QtGui.QPushButton(b_name, self))
            self.item_list.addItem(i_name)

        self.item_list.currentRowChanged.connect(self.stack.setCurrentIndex)


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

    widget.show()
    sys.exit(app.exec_())

Upvotes: 1

Views: 2643

Answers (1)

Brett Stottlemyer
Brett Stottlemyer

Reputation: 2852

Found this question while looking for a QStackedWidget example. May not be needed anymore, but I would consider not trying to re-arrange the order in the stacked widget. Instead, I would keep a python dictionary that uses the list names as the keys, and the index in the stack as the value. Then when the value of the list changes, lookup the index and set to that part of the stack.

Seems like much less work than trying to dynamically correct the stack.

Upvotes: 1

Related Questions