简体   繁体   中英

Change combobox values in Qt .ui file with PySide2

I'm using PySide2 to load a Qt Designer.ui file. I have a combobox called categoryBox, which is a child of MainWindow.centralwidget

I want to use Python to replace its contents with a list without changing the.ui file itself. However, I have no idea how I would find the combobox, and that's kind of important when it comes to replacing.

In short, I have a combobox. I don't know where I can find it, but I know where it is.

Relevant XML data from the.ui file:

<?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>

The code that opens the.ui file:

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_())

When using QUiLoader all objects are assigned as an attribute of the window using the objectName, in your case you should use:

window.categoryBox.addItems(["Foo", "Bar"])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM