Widgets

QPushbutton

Imports

```QtWidgets```

Declaration

```chromeButton = QPushButton("Chrome")```

Run code on click

        chromeButton.clicked.connect(self.setOutputChrome)

    def setOutputChrome(self):
        self.setOutput(self.plainTextEdit.toPlainText(), 'chrome', self.lineEdit.text(), self.lineEdit2.text())

QComboBox

PyQt4: QCombobox PyQt5: QCombobox Qt5 QCombobox

imports

```QtWidgets.QComboBox```

Allow user to add their own values / Disable

```myCombo.setEditable(False)```

QLabel

Imports

Attach to another control

This sets the label to be associated with another widget (a “buddy”):

    listLabel = QLabel(&List")
    self.listWidget = QListWidget()
    listLabel.setBuddy(self.listWidget)

QtMenu

Qt5 Menus example

Imports

from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (QMenu, QAction, QActionGroup)
from PyQt5.QtGui import QKeySequence

Create menu and assign to menubar

self.fileMenu = self.menuBar().addMenu("&File")

Assign command to a menu

self.fileMenu.addAction(self.dumpdbAct)

def createActions(self):
        # self.newAct = QAction("&New", self, shortcut=QKeySequence.New,
        #         statusTip="Create a new file", triggered=self.newFile)
        self.dumpdbAct = QAction("&Dump database", self, 
                  statusTip="Add a new book", triggered=self.addBook)
        self.promotebookAct = QAction("&Promote Book", self, 
                  statusTip="Add a new book", triggered=self.addBook)
        self.addbookAct = QAction("&Add Book", self, shortcut=QKeySequence.New,
                  statusTip="Add a new book", triggered=self.addBook)

    def createMenus(self):

        # Set up headline menus
        self.fileMenu = self.menuBar().addMenu("&File")
        self.editMenu = self.menuBar().addMenu("&Edit")
        self.seriesMenu = self.menuBar().addMenu("&Series")
        self.statusMenu = self.menuBar().addMenu("S&tatus")
        self.scanMenu = self.menuBar().addMenu("S&can")

        # set up file menu
        # self.fileMenu.addAction(self.newAct)
        # actions - dump database, export list (book, series etc.) to
        # csv etc.
        self.fileMenu.addAction(self.dumpdbAct)

QtAction

Used to unify actions across different methods of accessing the actions i.e. menu, keyboard

Create

self.dumpdbAct = QAction("&Dump database", self, 
                  statusTip="Add a new book", triggered=self.addBook)

Assign to a menu

self.fileMenu = self.menuBar().addMenu("&File")
self.fileMenu.addAction(self.dumpdbAct)

def createActions(self):
        # self.newAct = QAction("&New", self, shortcut=QKeySequence.New,
        #         statusTip="Create a new file", triggered=self.newFile)
        self.dumpdbAct = QAction("&Dump database", self, 
                  statusTip="Add a new book", triggered=self.addBook)
        self.promotebookAct = QAction("&Promote Book", self, 
                  statusTip="Add a new book", triggered=self.addBook)
        self.addbookAct = QAction("&Add Book", self, shortcut=QKeySequence.New,
                  statusTip="Add a new book", triggered=self.addBook)

    def createMenus(self):

        # Set up headline menus
        self.fileMenu = self.menuBar().addMenu("&File")
        self.editMenu = self.menuBar().addMenu("&Edit")
        self.seriesMenu = self.menuBar().addMenu("&Series")
        self.statusMenu = self.menuBar().addMenu("S&tatus")
        self.scanMenu = self.menuBar().addMenu("S&can")

        # set up file menu
        # self.fileMenu.addAction(self.newAct)
        # actions - dump database, export list (book, series etc.) to
        # csv etc.
        self.fileMenu.addAction(self.dumpdbAct)

QtActionGroup

Keeps a set of QtAction together. Normally exclusive - only one can be checked (c.f. radiobuttons) but behaviour can be turned off with exclusive = False

http://doc.qt.io/qt-4.8/qactiongroup.html http://doc.qt.io/qt-5/qactiongroup.html

Create

alignmentGroup = QActionGroup(self)

Add actions to group

alignmentGroup.addAction(leftAlignAct)
alignmentGroup.addAction(rightAlignAct)
alignmentGroup.addAction(justifyAct)
alignmentGroup.addAction(centerAct)

Check / activate one of the options

leftAlignAct.setChecked(true)

Layouts

QHBoxLayout

Imports

```QtQWidgets```

Declaration

```hbox = QHBoxLayout()```

Add widgets to layout

hbox.addWidget(chromeButton) hbox.addWidget(firefoxButton)

Options

hbox.addStretch(1)

Add highest layout to form

self.setLayout(hbox)

Windows and Dialogs

QMainWindow

Layouts

A Layout cannot be applied directly as the central (top-most) widget.

A blank or dummy widget must be created and the Layout inserted into the widget … as if it were a Layout.

        window = QWidget()
        window.setLayout(vbox)
        self.setCentralWidget(window)

QMessageBox

QMessageBox.critical(None, "Cannot open database",
                "Unable to establish a database connection.\n"
                "This example needs SQLite support. Please read the Qt SQL "
                "driver documentation for information how to build it.\n\n"
                "Click Cancel to exit.",
                QMessageBox.Cancel)

Collections

QStringList

http://pyqt.sourceforge.net/Docs/PyQt4/qstringlist.html http://pyqt.sourceforge.net/Docs/PyQt5/api/qstringlistmodel.html https://doc.qt.io/qt-5/qstringlistmodel.html

Notes: A Python list of strings can be used whenever a QStringList is expected and therefore this is unnecessary

Imports

```QtCore```

Function

QtSQL

from PyQt5.QtCore import Qt
from PyQt5.QtSql import QSqlQuery, QSqlQueryModel
from PyQt5.QtSql import QSqlDatabase, QSqlQuery

Create database connection

db = QSqlDatabase.addDatabase('QODBC3')
conn_str = (r'driver={ODBC Driver 13 for SQL Server};server=BASE2;port=1443;
UID=sa;PWD=9jFJg4F92vi7p6vT;database=AdventureWorks2012')
db.setDatabaseName(conn_str)
db.open()

Query the database

query = QSqlQuery()
query.exec_("""SELECT TOP(5) * FROM Person.Person""")

Get each record

while query.next():
    rec = query.record()
    for i in range(rec.count()):
    print(rec.value(i))

PyQt exit codes and output

Sample

class GatherText(QDialog):
...
self.output = {'Content':'', 'Browser':'', 'Modifier':'', 'Date':''}
...
self.accept()
...
if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = GatherText()
    # ex.exec_()
    # print('Content: \t' + ex.output['Content'] +
    #       '\nBrowser: \t' + ex.output['Browser'] +
    #       '\nDate: \t\t' + ex.output['Date'])
    # exit()
    sys.exit(app.exec_())

Normal use

If no return value is required:

    ex = GatherText()
    sys.exit(app.exec_())

This closes the dialog and exits the routine. For example, a program to zip files.

Obtain return values

To run the program and obtain the values:

    ex = GatherText()
    ex.exec_()
    print(ex.output)

This closes the dialog, exits the routine and makes any variables available for collection.

Test return values

To run the program and test for the output:

    ex = GatherText()
    ex.exec_()
    if ex.result() == 0:
        print('Cancelled', ex.output)
    if ex.result() == 1:
        print('1', ex.output)

Exit types

Use self.close(), self.reject(), self.accept(), self.done(int) in a function to exit the application.

    self.close() is 0
    self.reject() is 0
    self.accept() is 1
    self.done(int) is int value for edge cases

Right-click menu

Using Subclassing, Actions and Signal/Slot.

https://wiki.python.org/moin/PyQt/Handling%20context%20menus

QtContextMenu docs: https://doc.qt.io/archives/qtjambi-4.5.2_01/com/trolltech/qt/core/Qt.ContextMenuPolicy.html

ActionsContextMenu: https://doc.qt.io/archives/qtjambi-4.5.2_01/com/trolltech/qt/core/Qt.ContextMenuPolicy.html#ActionsContextMenu

Context Menu

Usually, the right mouse click is connected to the context menu. With

but.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
but.customContextMenuRequested.connect(handle_right_click)

you can connect a handler, which could be used for the right mouse click.

http://stackoverflow.com/questions/30627923/pyqt-python-creating-right-mouse-click-for-qpushbutton

Context menu policy

In the ControlMainWindow class add the following to initialise the Context menu policy as CustomContextMenu where listWidget_extractedmeters will be the name of your QListWidget:

self.listWidget_extractedmeters.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.listWidget_extractedmeters.connect(self.listWidget_extractedmeters,QtCore.SIGNAL("customContextMenuRequested(QPoint)" ), self.listItemRightClicked)

Then in the ControlMainwindow class the following functions allow you to add context menu items and to call a funtion that performs some functionality:

def listItemRightClicked(self, QPos): 
    self.listMenu= QtGui.QMenu()
    menu_item = self.listMenu.addAction("Remove Item")
    self.connect(menu_item, QtCore.SIGNAL("triggered()"), self.menuItemClicked) 
    parentPosition = self.listWidget_extractedmeters.mapToGlobal(QtCore.QPoint(0, 0))        
    self.listMenu.move(parentPosition + QPos)
    self.listMenu.show() 

def menuItemClicked(self):
    currentItemName=str(self.listWidget_extractedmeters.currentItem().text() )
    print(currentItemName)

http://stackoverflow.com/questions/31380457/add-right-click-functionality-to-listwidget-in-pyqt4

Links

http://joat-programmer.blogspot.co.uk/2012/02/pyqt-signal-and-slots-to-capture-events.html | Jack of all trades programmer: PyQt Signals and Slots http://pysnippet.blogspot.co.uk/2010/01/new-style-pyqt-signals-and-slots.html | PySnippet: New-style PyQt Signals and Slots http://www.cyberciti.biz/tips/howto-linux-unix-find-move-all-mp3-file.html | Finding All .mp3 Files And Move To a New Directory From A Shell Prompt - nixCraft http://www.pythoncentral.io/pyside-pyqt-tutorial-the-qlistwidget/?PageSpeed=noscript | PySide/PyQt Tutorial: The QListWidget - Python Central http://www.pythoncentral.io/pysidepyqt-tutorial-creating-your-own-signals-and-slots/?PageSpeed=noscript | PySide/PyQt Tutorial: Creating Your Own Signals and Slots - Python Central http://www.sthurlow.com/python/lesson06/ | Lesson 6 - Tuples, Lists, and Dictionaries http://www.qtcentre.org/threads/25705-How-to-add-subitem-in-treewidget | How to add subitem in treewidget http://qt-project.org/doc/qt-4.8/qtreewidgetitem.html | QTreeWidgetItem Class Reference | Documentation | Qt Project http://stackoverflow.com/questions/12737721/developing-pyqt4-tree-widget | qtreeview - Developing pyqt4 tree widget - Stack Overflow https://plus.google.com/103196608802087410670/posts/RQsvgvyJ4FS | Programming with Python - Google+ https://www.daniweb.com/software-development/python/threads/256274/pyqt-qspinbox-mouse | PyQT, QSpinBox, mouse | DaniWeb http://stackoverflow.com/questions/20898897/label-displays-sum-of-two-qspinbox-python-pyside | pyqt - label displays sum of two QSpinBox (Python + Pyside)? - Stack Overflow http://pyqt.sourceforge.net/Docs/PyQt4/qspinbox.html | QSpinBox Class Reference

http://rosettacode.org/wiki/Python | Category:Python - Rosetta Code

http://doc.qt.io/qt-5/qabstractitemview.html#EditTrigger-enum | QAbstractItemView Class | Qt Widgets 5.4 http://www.saltycrane.com/blog/?page=2 | SaltyCrane Blog http://thomas-cokelaer.info/blog/2012/10/pyqt4-example-of-tablewidget-usage/ | PyQt4: example of TableWidget usage | Thomas Cokelaer’s blog http://www.qtcentre.org/threads/37205-PyQt4-Inserting-data-from-array-to-QTableWidget | PyQt4 - Inserting data from array to QTableWidget http://pyqt.sourceforge.net/Docs/PyQt4/qtablewidgetitem.html | QTableWidgetItem Class Reference http://www.saltycrane.com/blog/2007/06/more-pyqt-example-code/ | More PyQt example code « SaltyCrane Blog http://stackoverflow.com/questions/11729472/adding-data-to-qtablewidget-using-pyqt4-in-python | pyqt - Adding data to QTableWidget using PyQt4 in Python - Stack Overflow http://zetcode.com/gui/pyqt4/ | PyQt4 tutorial http://qt-project.org/doc/qt-4.8/qstandarditemmodel.html#details | QStandardItemModel Class Reference | Documentation | Qt Project http://www.pythoncentral.io/pyside-pyqt-tutorial-qlistview-and-qstandarditemmodel/?PageSpeed=noscript | PySide/PyQT Tutorial: QListView and QStandardItemModel | Python Central http://qt-project.org/doc/qt-4.8/qstringlistmodel.html#details | QStringListModel Class Reference | Documentation | Qt Project http://www.bogotobogo.com/Qt/Qt5_QListView_QStringListModel_ModelView_MVC.php | Qt5 Tutorial ModelView with QListView and QStringListModel - 2015 http://zetcode.com/db/sqlitepythontutorial/ | SQLite Python tutorial http://www.pythoncentral.io/pyside-pyqt-tutorial-qlistview-and-qstandarditemmodel/?PageSpeed=noscript | PySide/PyQT Tutorial: QListView and QStandardItemModel | Python Central http://bytes.com/topic/python/answers/452460-pyqt-qlistview-how-retrieve-selected-items | PyQt: QListView how to retrieve selected items? - Python http://qt-project.org/forums/viewthread/28793 | Getting current index from a QListView model | Qt Project forums | Qt Project http://qt-project.org/forums/viewthread/25409 | [Solved] Signal when a QListView selection changes due to keyboard activity? | Qt Project forums | Qt Project http://qt-project.org/forums/viewthread/16059 | [SOLVED]How to get a selected item from QListWidget ? | Qt Project forums | Qt Project http://stackoverflow.com/questions/11246022/how-to-get-qstring-from-qlistview-selected-item-in-qt | How to get QString from QListView selected item in Qt? - Stack Overflow http://stackoverflow.com/questions/14546913/how-to-get-item-selected-from-qlistview-in-pyqt | python - How to get item selected from QListView in PyQt - Stack Overflow http://stackoverflow.com/questions/21313044/retrieve-selected-item-from-qlistview-pyqt | python - Retrieve selected item from QListView PyQt - Stack Overflow http://www.qtcentre.org/threads/32007-SetSelection-QListView-Pyqt | SetSelection QListView Pyqt http://zetcode.com/lang/python/strings/ | Strings in Python http://www.pythoncentral.io/pyside-pyqt-tutorial-the-qlistwidget/?PageSpeed=noscript | PySide/PyQt Tutorial: The QListWidget - Python Central http://en.wikibooks.org/wiki/Python_Programming/PyQt4 | Python Programming/PyQt4 - Wikibooks, open books for an open world http://www.riverbankcomputing.com/pipermail/pyqt/2012-March/031301.html | [PyQt] get list of selected items in a listWidget http://qt-project.org/doc/qt-4.8/qlistview.html#selectedIndexes | QListView Class Reference | Documentation | Qt Project http://stackoverflow.com/questions/19605302/how-to-get-the-selectionchange-event-in-pyqt4-for-qlistview | How to get the selectionchange event in PyQt4 for QListView - Stack Overflow http://pyqt.sourceforge.net/Docs/PyQt4/qstringlistmodel.html | QStringListModel Class Reference http://pyqt.sourceforge.net/Docs/PyQt4/qabstractitemmodel.html | QAbstractItemModel Class Reference http://pyqt.sourceforge.net/Docs/PyQt4/qstandarditemmodel.html | QStandardItemModel Class Reference http://www.qtcentre.org/threads/53618-QStringListModel-doesn-t-update-when-QStringList-is-updated | QStringListModel doesn’t update when QStringList is updated http://pyqt.sourceforge.net/Docs/PyQt4/qlistwidget.html | QListWidget Class Reference http://stackoverflow.com/questions/21566556/how-to-get-a-current-items-info-from-qtgui-qlistwidget | python - How to get a current Item’s info from QtGui.QListWidget? - Stack Overflow http://qt-project.org/doc/qt-4.8/model-view-programming.html | Model/View Programming | Documentation | Qt Project https://www.commandprompt.com/community/pyqt/x2976.htm | Basic widgets https://www.commandprompt.com/community/pyqt/x3270.htm | Advanced widgets