我正在使用PySide2加载Qt Designer .ui文件。我有一个名为categoryBox的组合框,它是MainWindow.centralwidget的子级
我想使用Python将其内容替换为列表,而不更改.ui文件本身。但是,我不知道如何找到组合框,这在更换时很重要。
简而言之,我有一个组合框。我不知道在哪里可以找到它,但是我知道它在哪里。
.ui文件中的相关XML数据:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>799</width>
<height>513</height>
</rect>
</property>
<property name="windowTitle">
<string>BlueCalculator</string>
</property>
<widget class="QWidget" name="centralwidget">
<widget class="QLabel" name="titleLabel">
<property name="geometry">
<rect>
<x>20</x>
<y>10</y>
<width>231</width>
<height>51</height>
</rect>
</property>
<property name="font">
<font>
<pointsize>26</pointsize>
</font>
</property>
<property name="text">
<string>BlueCalculator</string>
</property>
</widget>
<widget class="QComboBox" name="categoryBox">
<property name="geometry">
<rect>
<x>20</x>
<y>80</y>
<width>221</width>
<height>21</height>
</rect>
</property>
</widget>
打开.ui文件的代码:
import sys, os
from PySide2.QtUiTools import QUiLoader
from PySide2.QtWidgets import QApplication
from PySide2.QtCore import QFile, QIODevice
import os
rootdir = '.\\functions'
if __name__ == "__main__":
app = QApplication(sys.argv)
ui_file_name = "main.ui"
ui_file = QFile(ui_file_name)
if not ui_file.open(QIODevice.ReadOnly):
print("Cannot open {}: {}".format(ui_file_name, ui_file.errorString()))
sys.exit(-1)
loader = QUiLoader()
window = loader.load(ui_file)
ui_file.close()
if not window:
print(loader.errorString())
sys.exit(-1)
window.show()
sys.exit(app.exec_())
使用QUiLoader时,使用objectName将所有对象分配为窗口的属性,在这种情况下,您应该使用:
window.categoryBox.addItems(["Foo", "Bar"])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句