Qt对小部件样式和主题的支持使您的应用程序能够适应本机桌面环境。
在本教程中,我们将向您展示如何使用Qt for Python处理信号和插槽。Signals和slot是一个Qt特性【也可以说信号和插槽是QT的灵魂】,它允许图形小部件与其他图形小部件或python代码通信。我们的应用程序创建了一个按钮,记录点击的按钮,你好!每次单击python控制台时都会显示一条消息。
我们先导入必要的PySide6类和python sys模块:
import sys
from PySide6.QtWidgets import QApplication, QPushButton
from PySide6.QtCore import Slot
我们还要创建一个python函数,将消息记录到控制台:
# Greetings【您好】
@Slot()
def say_hello():
print("单击按钮, Hello!")
注意
@Slot()是一个将函数标识为插槽的装饰器。现在弄清它的原理并不重要,但要经常使用它来避免意外行为。
现在,如前面的示例所述,您必须创建QApplication来运行PySide6代码:
# Create the Qt Application
app = QApplication(sys.argv)
让我们创建clickable按钮,这是一个QPushButton实例。为了标记按钮,我们将一个python字符串传递给构造函数:
# Create a button
button = QPushButton("Click me")
在显示按钮之前,我们必须将它连接到前面定义的say_hello()函数。有两种方法可以做到这一点;使用旧的方式或新的方式。让我们在这种情况下使用新的书写方式。您可以在PySide6 Wiki页面的Signals和slot中找到关于这两种方式的更多信息。
QPushButton有一个预定义的信号,称为clicked,每次单击按钮时都会触发该信号。我们将此信号连接到say_hello()函数:
# Connect the button to the function
button.clicked.connect(say_hello)
最后,我们显示按钮并启动Qt主循环:
# Show the button
button.show()
# Run the main Qt loop
app.exec()
以下是此示例的完整代码:
#!/usr/bin/python
import sys
from PySide6.QtWidgets import QApplication, QPushButton
from PySide6.QtCore import Slot
@Slot()
def say_hello():
print("Button clicked, Hello!")
# Create the Qt Application
app = QApplication(sys.argv)
# Create a button, connect it and show it
button = QPushButton("Click me")
button.clicked.connect(say_hello)
button.show()
# Run the main Qt loop
app.exec()
以下是真实环境试验代码:
# This Python file uses the following encoding: utf-8
import sys
import PySide6.QtCore
from PySide6 import QtWidgets
from PySide6.QtWidgets import QApplication, QWidget, QPushButton, QLabel
from PySide6.QtGui import QIcon
from PySide6.QtCore import Slot
@Slot(QLabel)
def say_hello(labelx):
# print("Button clicked, Hello!")
labelx.setText("您好小蜘蛛!")
class button(QWidget):
def __init__(self):
QWidget.__init__(self)
if __name__ == "__main__":
app = QApplication([])
window = button()
window.setWindowIcon(QIcon('img/Search.ico'))
window.setWindowTitle("开软网络爬虫项目")
window.setFixedSize(600, 400) # 设置窗口固定大小
main_widget = QtWidgets.QWidget()
main_layout = QtWidgets.QVBoxLayout()
labelQ = QLabel("亲爱的 老公想你了")
labelQ.setAttribute(PySide6.QtCore.Qt.WA_StyledBackground, True)
labelQ.setStyleSheet('background-color: red; font-size:40px;')
labelQ.setAlignment(PySide6.QtCore.Qt.AlignCenter)
buttonQ = QPushButton("Click me")
buttonQ.clicked.connect(lambda: say_hello(labelQ))
main_layout.addWidget(labelQ)
main_layout.addWidget(buttonQ)
window.setLayout(main_layout)
window.show()
sys.exit(app.exec())
以下是试验截图: