前回のレッスンでは、PyQty5 のインストールと 2 つの環境の構成を学習しましたが、今日のレッスンでは、ボタンなどのウィジェットと機能のバインドについて学習し、これを学習した後は、自分でインターフェイスを設計できるようになります。独自の関数を記述して独自のガジェットを設計する
1. まず、新しい py ファイルを作成し、右クリックしてデザイン ウィンドウを開きます
2. 左側の[ボタン]をクリックし、[プッシュボタン]ボタンを3つドラッグし、ダブルクリックして名前を変更します
2. 閉じるボタンについては、最初に閉じる関数 ( 这一步先照着做一下
)でバインドします。
2-1 左上の矢印アイコンをクリックします
2-2 [ウィンドウを閉じる]ボタンをクリックし、空白の位置にドラッグします
2-3 以下のようにクリックします(F3で終了)
3. 2 つのボタンのオブジェクト名を変更します (ランダム)
4. シンプルな小さなウィンドウが作成されるので、[Ctrl+s] を押して保存しましょう
次に、前のセクションで構成した環境を使用して、設計したばかりの ui ファイルを py ファイルに変換します。同じ名前の py ファイルが生成されます。
5. 次に、オブジェクトを作成するコードを追加します。クラス名を変更することを忘れないでください。
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
mainWindow = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(mainWindow)
mainWindow.show()
sys.exit(app.exec_())
動画デモ、上記は問題ないようです
6. 次に、2 つのボタンを機能にバインドします。
6-1、まずボタンを見てみましょう
6-1、ボタンのバインド関数は次のとおりです。self.button.clicked.connect(绑定的函数)
バインドされた関数には括弧がないことに注意してください。
# -*- coding: utf-8 -*-
import sys
# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt5 UI code generator 5.15.6
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(400, 300)
self.nhbutton = QtWidgets.QPushButton(Dialog)
self.nhbutton.setGeometry(QtCore.QRect(90, 50, 201, 23))
self.nhbutton.setObjectName("nhbutton")
self.nhbutton.clicked.connect(self.print_nh)
self.hellobutton = QtWidgets.QPushButton(Dialog)
self.hellobutton.setGeometry(QtCore.QRect(90, 100, 201, 23))
self.hellobutton.setObjectName("hellobutton")
self.hellobutton.clicked.connect(self.print_hello_world)
self.pushButton_3 = QtWidgets.QPushButton(Dialog)
self.pushButton_3.setGeometry(QtCore.QRect(140, 150, 75, 23))
self.pushButton_3.setObjectName("pushButton_3")
self.retranslateUi(Dialog)
self.pushButton_3.clicked.connect(Dialog.reject) # type: ignore
QtCore.QMetaObject.connectSlotsByName(Dialog)
def print_nh(self):
print("你好")
def print_hello_world(self):
print("Hello World")
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.nhbutton.setText(_translate("Dialog", "点击按钮打印你好"))
self.hellobutton.setText(_translate("Dialog", "点击按钮打印HelloWorld"))
self.pushButton_3.setText(_translate("Dialog", "关闭窗口"))
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
mainWindow = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(mainWindow)
mainWindow.show()
sys.exit(app.exec_())