Python Examples

This page contains some python examples.

Sample PySide Application

#!/usr/bin/env python3

from PySide2 import QtCore, QtGui, QtWidgets
import PySide2

class MainWindow(QtWidgets.QMainWindow):

  def __init__(self):
    super(MainWindow, self).__init__()

    # Counter for toplevel records
    self.recCounter = 0

    # Counter for record items
    self.itemCounter = 0

    self.frame = QtWidgets.QFrame()
    self.frame.setBaseSize(100, 80)
    self.foo = QtWidgets.QComboBox(self.frame)
    self.completer = QtWidgets.QCompleter(["foo", "bar"])
    self.completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
    self.foo.setEditable(True)
    self.foo.setCompleter(self.completer)
    self.foo.addItem("foo")
    self.foo.addItem("bar")
    self.foo.currentIndexChanged.connect(self.fooChanged)
    self.frame.show()
    self.frame.resize(QtCore.QSize(200, 100))

    self.splitter = QtWidgets.QSplitter(QtCore.Qt.Horizontal)
    self.vLayout = QtWidgets.QVBoxLayout()
    self.vLayout.setSpacing(0)
    self.recList = QtWidgets.QListWidget()
    self.recList.itemClicked.connect(self.listClick)
    self.recTable = QtWidgets.QTableWidget()
    self.recTable.setLineWidth(2)
    self.recTable.setColumnCount(4)
    columnLabels = ["", "", "Name", "Value"]
    self.recTable.setHorizontalHeaderLabels(columnLabels)
    self.recTable.setColumnWidth(0, 30)
    self.recTable.setColumnWidth(1, 30)
    self.recTable.setColumnWidth(2, 200)
    self.recTable.setColumnWidth(3, 600)

    self.tableToolbar = QtWidgets.QToolBar("Item Actions")

    self.vLayout.addWidget(self.tableToolbar)
    self.vLayout.addWidget(self.recTable)

    self.splitter.addWidget(self.recList)
    self.vFrame = QtWidgets.QFrame()
    self.vFrame.setLayout(self.vLayout)
    self.splitter.addWidget(self.vFrame)
    self.setCentralWidget(self.splitter)
    self.splitter.setSizes([200, 800])

    self.createActions()
    self.createMenus()
    self.createToolBars()
    self.createStatusBar()

    self.tableToolbar.addAction(self.addTableItemAct)
    self.tableToolbar.addAction(self.delTableItemAct)

    self.readSettings()

    self.setUnifiedTitleAndToolBarOnMac(True)

    self.setWindowTitle("Test Application")

  def fooChanged(self):
    print("Value is: %s" % self.foo.itemText(self.foo.currentIndex()))

  def listClick(self):
    print("List clicked...")

  def close(self):
    super(MainWindow, self).close()

  def closeEvent(self, event):
    print("Exiting...")
    self.writeSettings()
    self.frame.close()
    event.accept()

  def save(self):
    print("Saving...")

  def new(self):
    self.recCounter += 1
    item = QtWidgets.QListWidgetItem("New Item " + str(self.recCounter))
    item.setFlags(item.flags() | QtCore.Qt.ItemIsEditable 
            | QtCore.Qt.ItemIsDragEnabled)
    item.setToolTip("This is a tool tip for an item")
    item.setStatusTip("This is a status tip for an item")
    self.recList.addItem(item)
    #self.recList.editItem(item)
    self.newItemRow()
    return True

  def newItemRow(self):
    self.itemCounter += 1
    rows = self.recTable.rowCount() + 1
    self.recTable.setRowCount(rows)

    delItem = self.recTable.setCellWidget(rows-1, 0, QtWidgets.QPushButton("X"))
#    self.recTable.cellWidget(rows-1, 0).setVisible(False)
    addItem = self.recTable.setCellWidget(rows-1, 1, QtWidgets.QPushButton("+"))
#    self.recTable.cellWidget(rows-1, 1).setVisible(False)

    nameItem = QtWidgets.QTableWidgetItem("Name " + str(self.itemCounter))
    self.recTable.setItem(rows-1, 2, nameItem)
    valueItem = QtWidgets.QTableWidgetItem("Value " + str(self.itemCounter))
    self.recTable.setItem(rows-1, 3, valueItem)

  def addTableItem(self):
    print("Called addTableItem()")

  def delTableItem(self):
    print("Called delTableItem()")

  def about(self):
    QtWidgets.QMessageBox.about(self, "About Application", "Test Application")

  def createActions(self):
    self.saveAct = QtWidgets.QAction(QtGui.QIcon('images/save.png'),
                                 "&Save", self, shortcut=QtGui.QKeySequence.Save,
                                 statusTip="Save the document to disk", triggered=self.save)

    self.newAct = QtWidgets.QAction(QtGui.QIcon('images/new.png'),
                                 "&New", self, shortcut=QtGui.QKeySequence.New,
                                 statusTip="Create new entry", triggered=self.new)

    self.exitAct = QtWidgets.QAction("E&xit", self, shortcut=QtGui.QKeySequence.Quit,
                                 statusTip="Exit the application", triggered=self.close)

    self.aboutAct = QtWidgets.QAction("&About", self,
                                  statusTip="About Application",
                                  triggered=self.about)

    self.addTableItemAct = QtWidgets.QAction("+", self, statusTip="Add new item to the record",
                                         triggered=self.addTableItem) 

    self.delTableItemAct = QtWidgets.QAction("X", self, statusTip="Delete selected item from the record",
                                         triggered=self.delTableItem) 

  def createMenus(self):
    self.fileMenu = self.menuBar().addMenu("&File")
    self.fileMenu.addAction(self.saveAct)
    self.fileMenu.addAction(self.newAct)
    self.fileMenu.addSeparator()
    self.fileMenu.addAction(self.exitAct)

    self.menuBar().addSeparator()

    self.helpMenu = self.menuBar().addMenu("&Help")
    self.helpMenu.addAction(self.aboutAct)

  def createToolBars(self):
    self.fileToolBar = self.addToolBar("File")
    self.fileToolBar.addAction(self.saveAct)
    self.fileToolBar.addAction(self.newAct)

  def createStatusBar(self):
    self.statusBar().showMessage("Ready")

  def readSettings(self):
    settings = QtCore.QSettings("Test", "TestApp")
    pos = settings.value("pos", QtCore.QPoint(200, 200))
    size = settings.value("size", QtCore.QSize(400, 400))
    self.resize(size)
    self.move(pos)

  def writeSettings(self):
    settings = QtCore.QSettings("Test", "TestApp")
    settings.setValue("pos", self.pos())
    settings.setValue("size", self.size())

  def saveFile(self, fileName):
    self.statusBar().showMessage("File saved", 2000)
    return True


print("PySide Version: " + PySide2.__version__)

if __name__ == '__main__':

  import sys

  app = QtWidgets.QApplication(sys.argv)
  mainWin = MainWindow()
  mainWin.show()
  sys.exit(app.exec_())
Code language: Python (python)