Skip to content
Advertisement

how to do a pagination bar in PyQT?

I need to paginate data from SQL tables.

I cant find any information about pagination in PyQT or Pyside. Can you help me pls?

like this

Advertisement

Answer

One way to handle pagination is to use the QStackedWidget for emulating the pages themselves, and regular QLabels as the page links. Then you can override each labels mousePressEvent to emit a signal to the stacked widget to set the current index to the page number from the label that was clicked.

Here is Minimal Reproducible Example using PySide6 that demonstrates the suggested strategy.

import sys
from PySide6.QtWidgets import *
from PySide6.QtCore import *
from PySide6.QtGui import *

class PageLink(QLabel):

    clicked = Signal([str])  # Signal emited when label is clicked

    def __init__(self, text, parent=None):
        super().__init__(text, parent=parent)
        self.setTextInteractionFlags(Qt.LinksAccessibleByMouse)
        self.setStyleSheet("color: blue;") # set text color to blue to emulate a link
        self.setCursor(Qt.PointingHandCursor)  # set the cursor to link pointer

    def mousePressEvent(self, event):
        self.clicked.emit(self.text())   # emit the clicked signal when pressed
        return super().mousePressEvent(event)


class MainWindow(QMainWindow):

    def __init__(self, parent=None) -> None:
        """Main Window Setup"""
        super().__init__(parent=parent)
        self.setWindowTitle("Pagination Demonstration")
        self.resize(600,400)
        self.central = QWidget(parent=self)
        self.layout = QVBoxLayout(self.central)
        self.setCentralWidget(self.central)

        # create the stacked widget that will contain each page...
        self.stackWidget = QStackedWidget(parent=self)
        self.layout.addWidget(self.stackWidget)

        # setup the layout for the page numbers below the stacked widget
        self.pagination_layout = QHBoxLayout()
        self.pagination_layout.addStretch(0)
        self.pagination_layout.addWidget(QLabel("<"))

        # create pages and corresponding labels
        for i in range(1, 6):
            page_link = PageLink(str(i), parent=self)
            self.pagination_layout.addWidget(page_link)
            page = QWidget()
            layout = QVBoxLayout(page)
            layout.addWidget(QLabel(f"This is page number {i} of 5"))
            self.stackWidget.addWidget(page)
            page_link.clicked.connect(self.switch_page)
        self.pagination_layout.addWidget(QLabel(">"))
        self.layout.addLayout(self.pagination_layout)

    def switch_page(self, page):
        self.stackWidget.setCurrentIndex(int(page) - 1)

app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement