Qt - Python Quick Reference

In this article we build a quick reference for much of the Qt Framework!

Qt - Python Quick Reference
  • One can spend a LOT of time finding these code example references that actually work, and are specific to the various widgets of Qt in the Python environment.
  • This is  a golden quick reference!
[Python Setting up Qt Environment]

    [Setting venv]

    python -m venv venv

    [Activating venv]

    source bin activate

    [Installing modules]

    python -m pip install module


[Qt Button] - Quick Reference

    #import example

    from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QPushButton, QFileDialog, QGraphicsScene, QGraphicsPixmapItem, QGraphicsView, QMessageBox, QToolTip

    Creation Example

    #region SubRegion [button_1]

    self.button_1 = QtWidgets.QPushButton(self.centralwidget)

    self.button_1.setObjectName("button_1")

    self.button_1.setText("Find Troughs")

    self.button_1.clicked.connect(self.button_1ClickedfindTroughs)

    self.horizontalLayout.addWidget(self.button_1)

    #endregion

    Set Size (Minimum / Maximum)

    self.pushButton.setMinimumSize(QtCore.QSize(20, 20))

    self.pushButton.setMaximumSize(QtCore.QSize(20, 20))

    Clicked Handler

    self.pushButton.clicked.connect(self.pushButtonAction)

    Set Rounded Corners

    button.setStyleSheet("border-radius : 50; border : 2px solid black")

    Change Background Color

    self.pushButton.setStyleSheet("background-color: red")

    Set Geometry

    button.setGeometry(200, 150, 100, 30)

    Set Button Icon

    button.setIcon(QIcon('logo.png'))


[Qt Slider] - Quick Reference

    #import example

    from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QPushButton, QFileDialog, QGraphicsScene, QGraphicsPixmapItem, QGraphicsView, QMessageBox, QToolTip, QSlider

    Creation Example

    #region SubRegion [slider_3neigh]

    self.slider_3 = QtWidgets.QSlider(self.centralwidget)

    self.slider_3.setOrientation(QtCore.Qt.Horizontal)

    self.slider_3.setMinimumSize(QtCore.QSize(120, 20))

    self.slider_3.setMaximumSize(QtCore.QSize(120, 20))

    self.slider_3.setMinimum(5)

    self.slider_3.setMaximum(1000)

    self.slider_3.valueChanged.connect(self.slider_3Change)

    self.slider_3.setObjectName("slider_3")

    self.horizontalLayout.addWidget(self.slider_3)

    #endregion

    Set Size (Minimum / Maximum)

    self.slider_3.setMinimumSize(QtCore.QSize(120, 20))

    self.slider_3.setMaximumSize(QtCore.QSize(120, 20))

    Value Changed Handler

    self.slider_3.valueChanged.connect(self.slider_3Change)

    # Inside the event handler

    def slider_2Change(self, event):

    mvalue = event # Will hold the number


[Qt Label] - Quick Reference

    #import example

    from PyQt5.QtWidgets import QLabel

    Creation Example

    "#region SubRegion [label_slider_1]

    self.label_1 = QtWidgets.QLabel(self.centralwidget)

    self.label_1.setObjectName("label_1")

    self.label_1.setText('smoothAvg: 1')

    self.horizontalLayout.addWidget(self.label_1)

    #endregion

    Set Size (Minimum / Maximum)

    self.label_1.setMinimumSize(QtCore.QSize(120, 20))

    self.label_1.setMaximumSize(QtCore.QSize(120, 20))

    Set Text

    self.label_1.setText("Label Text")


[Qt File Menu] - Quick Reference

    #import example

    from PyQt5.QtWidgets import QMenuBar, QFileDialog

    Part 1: Defining you Need a Menu Bar Itself

    self.menubar = QtWidgets.QMenuBar(MainWindow)

    self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 23))

    self.menubar.setObjectName("menubar")

    Part 2: Defining the The Main Menu 'File' - Two are shown here

    self.menuFile = QtWidgets.QMenu(self.menubar)

    self.menuFile.setObjectName("menuFile")

    self.menuFiletwo = QtWidgets.QMenu(self.menubar)

    self.menuFiletwo.setObjectName("menuFiletwo")

    self.menuFile.setTitle(_translate("MainWindow", "File"))

    self.menuFiletwo.setTitle(_translate("MainWindow", "Filetwo"

    Part 3: Defining Actions 'Open' under the File Menu main options

    self.actionOpen = QtWidgets.QAction(MainWindow)

    self.actionOpen.setObjectName("actionOpen")

    self.actionOpen.triggered.connect(self.menu_Open)

    self.menuFile.addAction(self.actionOpen)

    self.menubar.addAction(self.menuFile.menuAction())

    self.menuFiletwo.addAction(self.actionOpen)

    self.menubar.addAction(self.menuFiletwo.menuAction())

[Qt File Dialog] - Quick Reference

    #import example

    from PyQt5.QtWidgets import QFileDialog

    File Dialog Example

    self.fdialog = QtWidgets.QFileDialog()

    self.fdialog.setFileMode(QtWidgets.QFileDialog.ExistingFile)

    if self.fdialog.exec_():

    self.filename = str(self.fdialog.selectedFiles()[0])


QGraphicsView / QImage
[Qt QtWidgets.QGraphicsView] - Quick Reference

    Part 1: Main Creation Example (Overriding the base class)

    self.Draw_View = Draw_draw(self.gridLayoutWidget_2)

    self.Draw_View.setObjectName("graphicsView")

    self.Draw_View.setMouseTracking(True)

    self.gridLayout_2.addWidget(self.Draw_View, 0, 0, 1, 1)

    Part 2: Creating a override Draw Class

    class Draw_draw(QtWidgets.QGraphicsView):

    def __init__(self, parent):

    super(Mfft_draw, self).__init__(parent)

    Part 3: Overriding the Draw Function itself (7 parts)

    Part 3a: Defining a Image (Must Pre-fill)

    self.image = QImage(self.width, self.height, QImage.Format_RGB32)

    self.image.fill(QColor(220,220,220))

    Part 3b: Assigning a QPainter to Draw on the Image

    qpainter = QPainter(self.image)

    qpainter.setBrush(QColor(255,255,255))

    qpainter.setPen(QColor(20,20,20))

    Part 3c-1: Draw Line Example

    qpainter.drawLine(x1, y1, x2, y2)

    Part 3c-2: Draw Rectangle Example

    qpainter.drawRect(x1, y1, w, h)

    Part 4: Finish QPainter

    qpainter.end()

    Part 5: Create Pixmap

    self.pixmap = QPixmap.fromImage(self.image)

    Part 6: Create PixmapItem

    self.pixmapItem = QGraphicsPixmapItem(self.pixmap)

    Part 7: Create a Scene - Set Self to point to it

    scene = QGraphicsScene()

    scene.clear()

    scene.addItem(self.pixmapItem)

[Qt QtWidgets.QGraphicsView] - Scaling Quick Reference

    This scaling code will work for any QImage that is being hosted by the override class

    def resizeEvent(self, event):

    self.width = event.size().width()

    self.height = event.size().height()

    self.draw()

    def wheelEvent(self, event):

    #region Reference Scene Scaling Example

    zoom_factor = 1.15

    if event.angleDelta().y() > 0:

    self.scale(zoom_factor, zoom_factor)

    else:

    self.scale(1 / zoom_factor, 1 / zoom_factor)

    def mousePressEvent(self, event):

    if event.button() == Qt.LeftButton:

    self.startPos = event.pos()

    print(f"Setting self.startPos: {self.startPos}")

    self.click_mode = 'MOVE'

    else:

    self.startPos = None

    # Override the mouse press event for custom behavior

    epos = event.pos()

    scene_pos = self.mapToScene(event.pos())

    super().mousePressEvent(event)

    def mouseMoveEvent(self, event):

    if self.startPos is not None:

    # compute the difference between the current cursor position and the

    # previous saved origin point

    delta = self.startPos - event.pos()

    # get the current transformation (which is a matrix that includes the

    # scaling ratios

    transform = self.transform()

    # m11 refers to the horizontal scale, m22 to the vertical scale;

    # divide the delta by their corresponding ratio

    deltaX = delta.x() / transform.m11()

    deltaY = delta.y() / transform.m22()

    # translate the current sceneRect by the delta

    self.setSceneRect(self.sceneRect().translated(deltaX, deltaY))

    # update the new origin point to the current position

    self.startPos = event.pos()

    def mouseReleaseEvent(self, event):

    self.startPos = None


QTableView / QAbstractTableModel
  • It needs understanding that you typically create a QAbstractTableModel which is viewed through a TableView
[Qt QAbstractTableModel] - QAbstract Table Model

    This model is pretty typical for most QAbstractTableModel Views

    #region SubRegion [TableModel]

    class TableModel(QAbstractTableModel):

    def __init__(self, data=None):

    super().__init__()

    if data is not None:

    self.load_data(data)

    def load_data(self, data):

    if data is not None:

    self.data = data

    self.column_count = len(self.data[0])

    self.row_count = len(self.data)

    else:

    self.data = []

    self.column_count = 0

    self.row_count = 0

    def rowCount(self, parent=QModelIndex()):

    return len(self.data)

    def columnCount(self, parent=QModelIndex()):

    return len(self.data[0])

    def headerData(self, section, orientation, role):

    if role != Qt.DisplayRole:

    return None

    if orientation == Qt.Horizontal:

    return ("Col A", "Col B", "Difference")[section]

    else:

    return f"{section}"

    def setData(self, data):

    self.load_data(data)

    def data(self, index, role=Qt.DisplayRole):

    column = index.column()

    row = index.row()

    if role == Qt.DisplayRole:

    if 0 <= column <= 2:

    return str(self.data[row][column])

    elif role == Qt.BackgroundRole:

    return QColor(Qt.white)

    elif role == Qt.TextAlignmentRole:

    return Qt.AlignRight

    return None

    #endregion

  • Once you have that - it is simply a matter of pointing it to a table view
[Qt QtWidgets.QTableView] - QTableView

    #region SubRegion [tableWidget]

    self.tableWidget = TableViewAny(parent=self.horizontalLayoutWidget)

    self.tableWidget.setObjectName("tableWidget")

    self.tableWidget.clicked.connect(self.tableWidgetClicked)

    self.horizontalLayout.addWidget(self.tableWidget)

    #endregion

SelectionModel Example inside a QTableModel
  • Handling Table Selections (Selection Model)
  • You cannot hook to .mouseReleaseEvent it must be an inheritance override:
[Qt QtWidgets.QTableView] - Selection Model

    class TableViewAny(QtWidgets.QTableView):

    def __init__(self, parent=None):

    super().__init__(parent)

    def setData(self, data):

    pass

    def setModel(self, in_Model):

    super().setModel(in_Model)

    def mouseReleaseEvent(self, event):

    a = self.selectedIndexes()

    if self.selectionModel():

    selected_rows = self.selectionModel().selectedRows()

    selected_cells = self.selectionModel().selectedIndexes()

    for item in selected_cells:

    row = item.row()

    col = item.column()

    data = item.data(QtCore.Qt.DisplayRole)


More to follow as required!

Linux Rocks Every Day