跳转至

PyQt面向对象实现

Qt窗口继承

继承QWidget

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import sys


class MyWindow(QWidget):

    def __init__(self):
        super(MyWindow, self).__init__()
        self.setWindowTitle('title')


if __name__ == '__main__':
    app = QApplication(sys.argv)

    window = MyWindow()
    window.show()

    sys.exit(app.exec_())

通过继承QWidget来实现窗体

在构造中,必须实现super函数的调用,否则将出行错误

私有化

在python的类中,通常采用__名称来定义私有化的属性和函数。

私有化变量

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import sys


class MyWindow(QWidget):

    def __init__(self):
        super(MyWindow, self).__init__()
        self.setWindowTitle('title')

        self.__hello = 'hello'
        self.hi = 'hi'


if __name__ == '__main__':
    app = QApplication(sys.argv)

    window = MyWindow()
    window.__hello
    window.hi

    window.show()

    sys.exit(app.exec_())

在类中,定义了__hello_hi变量.

在外部使用过程中:

  • 第21行,window.__hello这个访问是不被允许的
  • 第22行,window.hi这个是可以访问的

私有化函数

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import sys


class MyWindow(QWidget):

    def __init__(self):
        super(MyWindow, self).__init__()
        self.setWindowTitle('title')
        self.__init_ui()

    def __init_ui(self):
        layout = QHBoxLayout()
        self.setLayout(layout)


if __name__ == '__main__':
    app = QApplication(sys.argv)

    window = MyWindow()

    window.__init_ui()

    window.show()

    sys.exit(app.exec_())

在类中,定义了__init_ui函数.

  • 第24行,外部调用此函数时,是无法访问的
  • 第12行,内部调用是可以的。

定义原则

  • 当属性只是当前类使用时,就将其作为私有的
  • 当函数只是当前类使用时,就将其作为私有的