開發環境:PyQt 5.5.1 Python 3.4.4 Qt 5.6.3
- Qt Creator新建項目
通過New File or Project->Qt Quick Controls UI新建一個項目,需勾選With ui.qml file。Ctrl+R運行程序,效果如下:
- PyQt程序編寫
參考教程 PyQt5 - Lesson 007. Works with QML QtQuick,在第一步中創建的項目目錄untitled下新建一個py文件,代碼如下:
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQml import QQmlApplicationEngine
if __name__ == "__main__":
import sys
# Create an instance of the application
app = QGuiApplication(sys.argv)
# Create QML engine
engine = QQmlApplicationEngine()
# Load the qml file into the engine
engine.load("untitled.qml")
engine.quit.connect(app.quit)
sys.exit(app.exec_())
效果如下:
3. 跟隨系統樣式
第二步中其風格沒有跟隨系統樣式,在 How to access native styles for qml apps? 找到了解決方法,即用QApplication替代QGuiApplication,代碼如下:
# from PyQt5.QtGui import QGuiApplication
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQml import QQmlApplicationEngine
if __name__ == "__main__":
import sys
# Create an instance of the application
app = QApplication(sys.argv)
# Create QML engine
engine = QQmlApplicationEngine()
# Load the qml file into the engine
engine.load("untitled.qml")
engine.quit.connect(app.quit)
sys.exit(app.exec_())