How to turn pages circularly in QStackedWidget in python?

1.2k views Asked by At

I made some pages in pyqt and then edited them in python.

I assume that there are 3 pages and I want this program to run 3 times, which means page1 to page2 to page3 to page1. I use the button 'Next' to connect each page.

I tried the loop. Here's my code which didn't work.

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from test import *

app = QApplication(sys.argv)
window = QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(window)

for i in range(3):
  def find_page():
      ui.stackedWidget.childern()
   window.visible = ui.stackedWidget.currentIndex()

  def next():
      ui.stackedWidget.setCurrentIndex(ui.stackedWidget.currentIndex()+1)
      print(window.visible)
  ui.next.clicked.connect(next)
window.show()
sys.exit(app.exec_())
1

There are 1 answers

0
Oliver On

Here is an example, based on your code, of how to change pages with stacked widget. You didn't post your UI file so I had to improvise other widgets. You'll have to change the imports for PyQt4, but the rest should be the same:

import sys

from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow, QStackedWidget

app = QApplication(sys.argv)

window = QMainWindow()
stack = QStackedWidget(parent=window)
label1 = QLabel('label1')
label2 = QLabel('label2')
label3 = QLabel('label3')
stack.addWidget(label1)
stack.addWidget(label2)
stack.addWidget(label3)
print('current', stack.currentIndex())
window.show()

def next():
      stack.setCurrentIndex(stack.currentIndex()+1)
      print('current', stack.currentIndex())

QTimer.singleShot(1000, next)
QTimer.singleShot(2000, next)
QTimer.singleShot(3000, next)
QTimer.singleShot(4000, app.quit)

sys.exit(app.exec_())