PyQt 实践教学(一)--First programs in PyQt5

本文章内容属于PyQt5学习笔记,学习资料为《PyQt5 tutorial》
挺好的一本用来入门的资料,尤其适合我这种之前没有学过Qt的渣….

Simple example(最简单的例子)

#! /usr/bin/python3
# coding = utf-8

import sys
from PyQt5.QtWidgets import QApplication,QWidget
if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = QWidget()
    w.resize(250, 150)
    w.move(300,300)
    w.setWindowTitle('Hello world')
    w.show()
    sys.exit(app.exec_())

Introduce:

  1. Every PyQt5 application must create an application object.
  2. The QWidget widget is the base class of all user interface objects in PyQt5. We provide the default constructor for QWidget. The default constructor has no parent. A widget with no parent is called a window.
  3. The show() method displays the widget on the screen. A widget is first created in memory and later shown on the screen.
  4. Finally, we enter the mainloop of the application. The event handling starts from this point. The mainloop receives events from the window system and dispatches them to the application widgets. The mainloop ends if we call the exit() method or the main widget is destroyed. The sys.exit()method ensures a clean exit. The environment will be informed how the application ended.
    The exec_() method has an underscore. It is because the exec is a Python keyword. And thus, exec_() was used instead.

An application icon(设置程序图标)

#! /usr/bin/python3
# coding = utf-8
import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QIcon

class Example(QWidget):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        # x轴位置,y轴位置,x轴长度,y轴长度
        self.setGeometry(300, 300, 300, 300)
        self.setWindowTitle('Icon')
        self.setWindowIcon(QIcon("icons/icon.jpg"))

        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())
  1. The creation of the GUI is delegated to the initUI() method.
  2. initUI(self):
    All three methods have been inherited from the QWidget class. The setGeometry() does two things: it locates the window on the screen and sets it size. The first two parameters are the x and y positions of the window. The third is the width and the fourth is the height of the window. In fact, it combines the resize() and move() methods in one method. The last method sets the application icon. To do this, we have created a QIcon object. The QIcon receives the path to our icon to be displayed

Showing a tooltip(显示悬停信息)

#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""悬停提示信息"""
import sys
from PyQt5.QtWidgets import (QWidget, QToolTip, QPushButton, QApplication)
from PyQt5.QtGui import QFont

class Example(QWidget):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        QToolTip.setFont(QFont('SansSerif', 10))

        self.setToolTip('This is a <b>QWidget</b> widget')

        btn = QPushButton('悬停显示提示', self)
        btn.setToolTip('This is a <b>QPushButton</b> widget')
        btn.resize(btn.sizeHint())
        btn.move(50, 50)

        self.setGeometry(300, 300, 300, 300)
        self.setWindowTitle("显示浮动提示信息")
        self.show()
if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

    QToolTip.setFont(QFont('SansSerif', 10))
  1. This static method sets a font used to render tooltips. We use a 10px SansSerif font.
  2. The sizeHint() method gives a recommended size for the button.

Closing a window(关闭窗口)

#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""用按钮关闭程序"""
import sys
from PyQt5.QtWidgets import QWidget, QPushButton, QApplication
from PyQt5.QtCore import QCoreApplication
# signal & slot mechanism.信号槽机制

class Example(QWidget):
    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):
        # 按钮的第二个参数是它的父组件 parent widgets
        qbtn = QPushButton('Quit', self)
        qbtn.clicked.connect(QCoreApplication.instance().quit)
        qbtn.resize(qbtn.sizeHint())
        qbtn.move(50, 50)

        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('Quit button test')
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())
  1. The event processing system in PyQt5 is built with the signal & slot mechanism.
    If we click on the button, the signal clicked is emitted. The slot can be a Qt slot or any Python callable. The QCoreApplication contains the main event loop; it processes and dispatches all events. The instance()method gives us its current instance. Note that QCoreApplication is created with the QApplication.
    The clicked signal is connected to the quit() method which terminates the application. The communication is done between two objects: the sender(quit按钮) and the receiver(应用程序对象). The sender is the push button, the receiver is the application object.

Message Box(消息窗口)

# -*- coding: utf-8 -*-
"""消息窗口示例"""
import sys
from PyQt5.QtWidgets import QWidget, QMessageBox, QApplication
class Example(QWidget):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle("消息窗口演示程序")
        self.show()

    def closeEvent(self, event):
        reply = QMessageBox.question(self, 'Message',  'Are you sure to quit?',QMessageBox.Yes | QMessageBox.No,QMessageBox.No)
        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()
if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())
QMessageBox.question(self, 'Message',  'Are you sure to quit?',QMessageBox.Yes | QMessageBox.No,QMessageBox.No)
  1. We show a message box with two buttons: Yes and No.
    The first string appears on the titlebar.
    The second string is the message text displayed by the dialog.
    The third argument specifies the combination of buttons appearing in the dialog.
    The last parameter is the default button. It is the button which has initially the keyboard focus.
    The return value is stored in the reply variable
if reply == QMessageBox.Yes:
    event.accept() 
else:
    event.ignore()
  1. Here we test the return value. If we click the Yes button, we accept the event which leads to the closure of the widget and to the termination of the application. Otherwise we ignore the close event.

Centering window on the screen(把窗口放在屏幕中心)

#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""窗口置中"""
import sys
from PyQt5.QtWidgets import QWidget,QDesktopWidget,QApplication
class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.resize(500, 500)
       self.center()

        self.setWindowTitle("窗口置中程序")
        self.show()

    def center(self):
        # 获得这个QT组件的框架位置QT rectangle
        qr = self.frameGeometry()
        # 找到我们屏幕的center point
        cp = QDesktopWidget().availableGeometry().center()
        # 现在我们将这个矩形的中心放在当前这个屏幕的中心
        qr.moveCenter(cp)
        # move the top-left point of app to the top-left of the qr rectangle
        self.move(qr.topLeft())

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())
  1. We get a rectangle specifying the geometry of the main window. This includes any window frame.
    qr = self.frameGeometry()
  2. We figure out the screen resolution of our monitor. And from this resolution, we get the center point
    cp = QDesktopWidget().availableGeometry().center()
  3. Our rectangle has already its width and height. Now we set the center of the rectangle to the center of the screen. The rectangle’s size is unchanged.
    qr.moveCenter(cp)
  4. We move the top-left point of the application window to the top-left point of the qr rectangle, thus centering the window on our screen
    self.move(qr.topLeft())

In this part of the PyQt5 tutorial, we covered some basics.

    原文作者:东皇Amrzs
    原文地址: https://www.jianshu.com/p/0afcc664c636
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞