版权声明: https://blog.csdn.net/jeremyjone/article/details/81013180
上一篇认识了PySide,为了快速开发我们第一个测试小项目,今天主要编写窗体,里面的数据实现后面再说。
测试小项目的效果图参考第一篇文章。
首先分析一下项目需求,我们需要从一个json文件中读取数据,然后按层级关系显示在窗体中。
{
"$schema": "http://json-schema.org/draft-04/schema",
"label": "FFM",
"type": "menu",
"description": "XXX",
"items": [
{
"label": "File",
"type": "menu",
"description": "",
"items" : [
{
"label": "Export",
"type": "command",
"description": "",
"file": "ffm_export.py",
"command": "main.show()"
},
{
"label": "Import",
"type": "command",
"description": "",
"file": "ffm_import.py",
"command": "main.show()"
}
]
}
]
}
这是json文件的一部分,在这里分析一下,要在树结构中显示label字段,遇到items字段时会有子项,而且items是列表结构,其余都是字典结构。
综上,我们需要很简单的窗体结构,左边需要一个树状结构,右边是一个label结构。
上一篇文章已经知道如何创建PySide中的widget以及显示它,那么我们只需要找到对应的widget并且正确显示就好了。
我们在这里用到Qt Designer,很简单就可以实现。
保存之后,可以看到ui文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Form</class>
<widget class="QWidget" name="Form">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>656</width>
<height>460</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<widget class="QTreeView" name="treeView">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>291</width>
<height>451</height>
</rect>
</property>
</widget>
<widget class="QTableWidget" name="tableWidget">
<property name="geometry">
<rect>
<x>290</x>
<y>0</y>
<width>361</width>
<height>451</height>
</rect>
</property>
</widget>
</widget>
<resources/>
<connections/>
</ui>
其实就是个xml文件,然后我们通过命令编译为py文件
pyside-uic .\mainWindow.ui -o .\mainWindow.py
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(602, 502)
self.treeView = QtGui.QTreeView(Form)
self.treeView.setGeometry(QtCore.QRect(1, 1, 250, 500))
self.treeView.setObjectName("treeView")
self.tableWidget = QtGui.QTableWidget(Form)
self.tableWidget.setGeometry(QtCore.QRect(250, 1, 350, 500))
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(0)
self.tableWidget.setRowCount(0)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(QtGui.QApplication.translate("Form", "Window", None, QtGui.QApplication.UnicodeUTF8))
这样就感觉顺眼多了吧。
之后我们改改名字,最好改成有实际意义的名字。当然也可以不管它!(我就懒得改了)
现在,最基本的界面已经做出来了,有木有很简单!我们让它初始化运行一下。
和预想的完全一样,左边是一个树结构,右边是一个table结构,我们可以往里面填数据了。
创建窗体大体就是这样,更复杂的使用这样的方式可以更加快速的开发,大大减少了代码量,灵活运用吧。
总结,窗体的实现要有大体的思路,知道大概用什么widget,实现快速开发。