Skip to content

Instantly share code, notes, and snippets.

@joshbarrass
Created February 25, 2019 16:22
Show Gist options
  • Save joshbarrass/75e369b08110b2ef8c4f0e4572c37267 to your computer and use it in GitHub Desktop.
Save joshbarrass/75e369b08110b2ef8c4f0e4572c37267 to your computer and use it in GitHub Desktop.
Simple PyQt5 program to serve as an example/base for future programs.
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtWidgets import QPushButton, QWidget, QLabel
from PyQt5.QtWidgets import QHBoxLayout, QVBoxLayout
class MyMainWindow(QMainWindow):
''' the main window potentially with menus, statusbar, ... '''
def __init__(self):
super().__init__() # calls __init__ of the parent class, QMainWindow
# initialise anything specific to our derived MyMainWindow class
self.resize(600, 300)
self.move(300, 200)
self.setWindowTitle('An empty PyQt QMainWindow')
self.statusBar().showMessage("Waiting for button")
central_widget = MyCentralWidget(self)
self.setCentralWidget(central_widget)
class MyCentralWidget(QWidget):
''' everything in the main area of the main window '''
def __init__(self, main_window): # main_window provided to access parent window
super().__init__()
self.main_window = main_window
# define left button with method to be called
left_button = QPushButton('Left', self) # second argument specifies it goes in this widget
left_button.move(100,100)
left_button.clicked.connect(self.leftclicked)
# define right button
right_button = QPushButton('Right', self)
right_button.move(700,100)
right_button.clicked.connect(self.rightclicked)
# define label
self.label = QLabel(self)
self.label.setText("Press a button!")
self.label.adjustSize()
self.left_times, self.right_times = (0,0)
# place the buttons into a horizontal box layout
hbox = QHBoxLayout()
hbox.addWidget(left_button) # add the left button
hbox.addStretch(1) # add an expanding box
hbox.addWidget(right_button) # add the right button
# place this box and the label into a vertical box layout
vbox = QVBoxLayout()
vbox.addStretch(1)
vbox.addLayout(hbox)
vbox.addStretch(1)
vbox.addWidget(self.label)
#use the box layout as the layout for the window
self.setLayout(vbox)
def leftclicked(self):
self.main_window.statusBar().showMessage("Left button clicked")
self.left_times += 1
self.update_label()
def rightclicked(self):
self.main_window.statusBar().showMessage("Right button clicked")
self.right_times += 1
self.update_label()
def update_label(self):
self.label.setText(f"Left: {self.left_times} Right: {self.right_times}")
self.label.adjustSize()
app = None
def main():
global app
app = QApplication(sys.argv)
w = MyMainWindow()
w.show() # display the window on the screen (could be included in initUI() instead)
app.exec() # run the application
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment