在 PySide6 中,“调用 Python”的含义通常是指:

在 PySide6 的 UI 组件中(如按钮、输入框、信号槽)调用 Python 函数或逻辑代码,即 前端控件触发后端处理逻辑


✅ 示例场景:点击按钮调用 Python 函数

这是 PySide6 最典型的用法场景。

🔧 安装 PySide6(如果还没安装):

pip install PySide6

✅ 最小工作示例

from PySide6.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QMessageBox

# 你要调用的 Python 函数
def say_hello():
    QMessageBox.information(None, "Python函数", "Hello from Python!")

app = QApplication([])

window = QWidget()
window.setWindowTitle("PySide6 调用 Python 示例")

# 创建一个按钮
button = QPushButton("点我调用 Python")

# 绑定按钮点击信号到函数
button.clicked.connect(say_hello)

layout = QVBoxLayout()
layout.addWidget(button)
window.setLayout(layout)

window.show()
app.exec()

✅ 输出效果

  • 点击按钮后,会弹出一个 QMessageBox 弹窗,说明已经调用了 say_hello() 这个 Python 函数。

✅ 更多控件调用 Python 示例

控件调用 Python 示例
QLineEdit 文本输入绑定 .textChanged.connect(your_function)
QComboBox 下拉菜单绑定 .currentIndexChanged.connect(func)
QCheckBox 选中状态绑定 .stateChanged.connect(func)
QTimer 定时触发.timeout.connect(func)
自定义信号使用 @Signal + emit() 触发逻辑

✅ 自定义 Python 类/逻辑被调用

你也可以调用复杂类中的方法,例如:

class Processor:
    def run(self):
        print("后台处理逻辑执行了")

processor = Processor()
button.clicked.connect(processor.run)

✅ 补充:使用 QML 调用 Python(高级场景)

如果你使用的是 Qt Quick/QML 前端,可通过 @Slot 注解暴露 Python 方法给 QML 组件调用:

from PySide6.QtCore import QObject, Slot
from PySide6.QtQml import QQmlApplicationEngine

class Backend(QObject):
    @Slot()
    def doSomething(self):
        print("QML 调用了 Python")

app = QApplication([])
engine = QQmlApplicationEngine()
backend = Backend()
engine.rootContext().setContextProperty("backend", backend)
engine.load("main.qml")
app.exec()

然后在 main.qml 中:

Button {
    text: "调用 Python"
    onClicked: backend.doSomething()
}

✅ 总结

用法描述
.clicked.connect(py_func)最常用方式,控件信号绑定到 Python 函数
.textChanged.connect(...) 等输入框、组合框等交互信号
使用 QTimerQThread可用于后台执行、定时任务
@Slot 注解在 QML 中调用 Python 函数时需要