运行需要安装pyside6。
pip install pyside6 -i https://pypi.douban.com/simple/
创建main.py文件,python代码注释如下:
import osfrom pathlib import Pathimport sysfrom PySide6.QtCore import Property, QUrlfrom PySide6.QtGui import QGuiApplication, QPen, QPainter, QColorfrom PySide6.QtQml import qmlRegisterTypefrom PySide6.QtQuick import QQuickPaintedItem, QQuickView, QQuickItemclass PieSlice (QQuickPaintedItem): def __init__(self, parent=None): QQuickPaintedItem.__init__(self, parent) self._color = QColor() @Property(QColor) def color(self): return self._color @color.setter def color(self, value): self._color = value def paint(self, painter): pen = QPen(self._color, 2) painter.setPen(pen) painter.setRenderHints(QPainter.Antialiasing, True) painter.drawPie(self.boundingRect().adjusted(1, 1, -1, -1), 90 * 16, 290 * 16)class PieChart (QQuickItem): def __init__(self, parent=None): QQuickItem.__init__(self, parent) self._name = None self._pieSlice = None @Property(str) def name(self): return self._name @name.setter def name(self, value): self._name = value @Property(PieSlice) def pieSlice(self): return self._pieSlice @pieSlice.setter def pieSlice(self, value): self._pieSlice = value self._pieSlice.setParentItem(self)if __name__ == '__main__': app = QGuiApplication(sys.argv) qmlRegisterType(PieChart, 'Charts', 1, 0, 'PieChart')#注册类 qmlRegisterType(PieSlice, "Charts", 1, 0, "PieSlice") view = QQuickView() view.setResizeMode(QQuickView.SizeRootObjectToView) qml_file = os.fspath(Path(__file__).resolve().parent / 'app.qml') view.setSource(QUrl.fromLocalFile(qml_file)) if view.status() == QQuickView.Error: sys.exit(-1) view.show() res = app.exec() del view sys.exit(res)
创建app.qml界面文件,代码注释如下:
import Chartsimport QtQuickItem { width: 300; height: 200 PieChart { id: chart anchors.centerIn: parent width: 100; height: 100 pieSlice: PieSlice { anchors.fill: parent color: "blue" } } Text { id: t1 anchors { bottom: parent.bottom; horizontalCenter: parent.horizontalCenter; bottomMargin: 20 } text: "当前颜色" + chart.pieSlice.color } Component.onCompleted: console.log("The pie is colored " + chart.pieSlice.color);}
版权声明:内容来源于互联网和用户投稿 如有侵权请联系删除