4

Hello PyQt/PySide experts,

I am a newbie to both PyQt/PySide and desktop application development (I'm a web developer).

I have a question about how you should navigate among different views in a PyQt/PySide application.

Suppose my app has views (i.e. like pages in a web app) "TEST1"(default) and "TEST2", and I want to switch between them by clicking on the corresponding toolbar item.

I thought I could use QMainWindow.setCentralWidget() to set the requested view each time the toolbar button is clicked, but is this a normal way to navigate among different views in PyQt/PySide?

For your reference, I will post an example code to illustrate the above:

#!/usr/bin/env python

import sys
from PySide import QtCore
from PySide.QtCore import *
from PySide.QtGui import *

class MainWindow(QMainWindow):

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        # toolbar action 1
        self.test1_action = QAction(QIcon('icons/test1.png'), 'Test 1', self)
        self.test1_action.triggered.connect(self.show_test1_view)

        # toolbar action 2
        self.test2_action = QAction(QIcon('icons/test2.png'), 'Test 2', self)
        self.test2_action.triggered.connect(self.show_test2_view)

        # create toolbar
        self.toolbar = self.addToolBar('Actions')
        self.toolbar.addAction(self.test1_action)
        self.toolbar.addAction(self.test2_action)

        # default view is test1, so call the method to set the central widget to "test1" view.
        self.show_test1_view()

    # switch to "test1" view - just a simple label here.
    def show_test1_view(self):
        self.test1_view = QLabel('TEST1 VIEW')
        self.setCentralWidget(self.test1_view)

    # switch to "test2" view - just a simple label here.
    def show_test2_view(self):
        self.test2_view = QLabel('TEST2 VIEW')
        self.setCentralWidget(self.test2_view)

app = QApplication(sys.argv)

window = MainWindow()
window.show()

app.exec_()
sys.exit()

Thank you in advance...!

Sacki
  • 137
  • 3
  • 10

1 Answers1

5

stackedwidget might do the trick

dugres
  • 12,613
  • 8
  • 46
  • 51
  • Hello, thanks for point that out! I have taken a look at it, and it sure looks good for my purposes. But is using the StackedWidget de-facto standard for apps like mine? What would you normally use in the situation like mine? Thanks! – Sacki Aug 08 '11 at 07:02
  • @Sacki : I do use StackedWidget, I don't know if it's a "standard" of any sort, but it must exist for a reason. And I think that the reason it exists is to be used when needed ... :) – dugres Aug 08 '11 at 07:53
  • Hi there, thanks for your reply, and I am sorry it took me long to get back to you. I will definitely give it a try. Thanks again! – Sacki Aug 11 '11 at 19:53