![](/img/trans.png)
[英]PySide2 (Qt for Python) how to load a .ui file in a QMainWindow subclass
[英]Change combobox values in Qt .ui file with PySide2
我正在使用 PySide2 加載 Qt Designer.ui 文件。 我有一個名為 categoryBox 的 combobox,它是 MainWindow.centralwidget 的一個孩子
我想使用 Python 將其內容替換為列表而不更改 .ui 文件本身。 但是,我不知道如何找到 combobox,這在更換時很重要。
簡而言之,我有一個 combobox。 我不知道在哪里可以找到它,但我知道它在哪里。
來自.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 的屬性,在您的情況下,您應該使用:
window.categoryBox.addItems(["Foo", "Bar"])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.