文章目录
Pyside6使用QML做UI开发时调试
一个项目,需要做个单机版程序,由于涉及后期数据分析,打算用python作为开发语言,在UI的工具这块,尝试了Streamlit,但streamlit每次刷新都会重新加载代码,由于涉及到串口通信,Streamlit无法正常使用,故还是选择用了QT官方的pyside6,UI使用QML。
但在程序编写时发现,QML代码中使用的console.log无法正常输出,并且和使用QT C++开发不同,QML代码中也无法使用断点。
再查阅了诸多资料,找到一篇QT官方的帖子
https://doc.qt.io/qtforpython-6/tutorials/debugging/qml_debugging.html
但我使用该代码后,程序直接异常闪退,无法正常调试输出,后再查阅资料和尝试,发现只要再main.py中增加2行代码即可
# This Python file uses the following encoding: utf-8
import sys
from pathlib import Path
from PySide6.QtGui import QGuiApplication
from PySide6.QtQml import QQmlApplicationEngine
from PySide6.QtQml import QQmlDebuggingEnabler # 1. 导入QQmlDebuggingEnabler包
if __name__ == "__main__":
QQmlDebuggingEnabler.enableDebugging(True) # 2. 使能QML debug功能
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
qml_file = Path(__file__).resolve().parent / "main.qml"
engine.load(qml_file)
if not engine.rootObjects():
sys.exit(-1)
sys.exit(app.exec())
再main.qml中增加鼠标点击进行测试
import QtQuick
import QtQuick.Window
Window {
width: 640
height: 480
visible: true
title: qsTr("Hello World")
// 放置一个矩形,并增加鼠标点击事件
Rectangle {
anchors.fill: parent
color: 'blue'
MouseArea {
anchors.fill: parent
onClicked: {
console.log('clicked')
}
}
}
}
在 console.log这里放个断点,点击左侧的调试运行按钮,单级窗体蓝色区域,可以正常进入断点,且在 QTCreator底部的 QML Debug Console窗口里能够看到clicked输出