【问题标题】:Change combobox values in Qt .ui file with PySide2使用 PySide2 更改 Qt .ui 文件中的组合框值
【发布时间】:2020-11-27 09:01:44
【问题描述】:

我正在使用 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_())

【问题讨论】:

    标签: python qt-designer pyside2


    【解决方案1】:

    使用 QUiLoader 时,所有对象都使用 objectName 指定为窗口的属性,在您的情况下,您应该使用:

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

    【讨论】:

      猜你喜欢
      • 2019-06-12
      • 1970-01-01
      • 1970-01-01
      • 2017-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多