GUI can be fun but choosing the right library for the job can be daunting task. I recently evaluated several libraries GTK,wxWidgets and other libraries. and finally settled on Qt. and PyQt5 is great because it is easy to integrate with python application.
This is hello world and explanation to create and populate PyQt5 widgets.
Starting with QApplication
instantiated from QtWidgets. The typical PyQt5 skelton uses and class from QMainWindow
. In this example, it’s called MainWindow
.
app = QtWidgets.QApplication(sys.argv)
main = MainWindow()
sys.exit(app.exec_())
First widget is the QLabel
with a lot of text to show the scroll functionality. and add the layout and add layout and then add layout to wrapper widget.
for i in range(1,50):
object = QLabel("TextLabel")
self.vbox.addWidget(object)
self.widget.setLayout(self.vbox)
The next step is to configure the scroll widget and add the widget created above in the scroll window.
self.scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.scroll.setWidgetResizable(True)
self.scroll.setWidget(self.widget)
finally, we add the scroll widget the current main app object.
self.setCentralWidget(self.scroll)
Finally, configure few parameters in the main object and call show
and we are golden.
self.setGeometry(600, 100, 1000, 900)
self.setWindowTitle('Scroll Area Demonstration')
self.show()
The full example Link to heading
from PyQt5.QtWidgets import (QWidget, QSlider, QLineEdit, QLabel, QPushButton, QScrollArea,QApplication,
QHBoxLayout, QVBoxLayout, QMainWindow)
from PyQt5.QtCore import Qt, QSize
from PyQt5 import QtWidgets, uic
import sys
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.scroll = QScrollArea() # Scroll Area which contains the widgets, set as the centralWidget
self.widget = QWidget() # Widget that contains the collection of Vertical Box
self.vbox = QVBoxLayout() # The Vertical Box that contains the Horizontal Boxes of labels and buttons
for i in range(1,50):
object = QLabel("TextLabel")
self.vbox.addWidget(object)
self.widget.setLayout(self.vbox)
#Scroll Area Properties
self.scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.scroll.setWidgetResizable(True)
self.scroll.setWidget(self.widget)
self.setCentralWidget(self.scroll)
self.setGeometry(600, 100, 1000, 900)
self.setWindowTitle('Scroll Area Demonstration')
self.show()
return
def main():
app = QtWidgets.QApplication(sys.argv)
main = MainWindow()
sys.exit(app.exec_())
if __name__ == '__main__':
main()