在单独的类方法/函数中获取由事件触发的 QComboBox 项目文本 [英] Get QComboBox item text triggered by event in separate class method/function

查看:66
本文介绍了在单独的类方法/函数中获取由事件触发的 QComboBox 项目文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法从 QComboBox 获取除函数中的索引以外的任何信息.大多数类似的示例提供与触发事件相同的类中的函数.我正在尝试从外部类(和文件)中获取此信息.

I'm having trouble getting any information from a QComboBox other than the index in a function. Most similar examples provides the function in the same class as the triggered event. I'm trying to get this from an external class (and file).

文件夹结构如此处的答案所示:

Folder structure is as provided in the answer here:

在paintEventTest.py 中,我创建了一个列表,用于用项目填充组合框.ComboEvent 是从 EventMethods.py 实例化的,我正在尝试在我的函数中打印 itemText.

In paintEventTest.py I've created a list which is used to populate the combobox with items. ComboEvent is instantiated from EventMethods.py and I'm trying to print the itemText in my function.

EventMethods.py

EventMethods.py

from PySide2.QtWidgets import QWidget, QPushButton, QComboBox

class widgetEventHandler(QWidget):

    def closeEvent(self, event):
        print("TEST")


class comboBoxEvent(QComboBox):
    def getSectionShape(self, index):
        text = str(self.itemText(index))
        print(text)
        print("Index changed to: " + str(index))

paintEventTest.py

paintEventTest.py

import sys

from PySide2 import QtWidgets 
from PySide2 import QtGui
from PySide2 import QtCore
from PySide2.QtUiTools import QUiLoader
from PySide2.QtWidgets import (
    QApplication, QPushButton, QLineEdit, QTextEdit, QSpinBox, QMainWindow, QDesktopWidget, QTableWidget, 
    QTableWidgetItem, QToolButton, QToolTip)
from PySide2.QtCore import QFile, QObject, Qt

from EventMethods import *


class MainForm(QMainWindow):
    def __init__(self, ui_file, parent=None):
        super(MainForm, self).__init__(parent)
        ui_file = QtCore.QFile(ui_file)
        ui_file.open(QtCore.QFile.ReadOnly)

        ### Load UI file from Designer ###
        loader = QUiLoader()
        self.ui_window = loader.load(ui_file)
        ui_file.close()
        self.ui_window.show()

        #region widget code
        widget = self.ui_window.widget
        widget.setStyleSheet("""
            QWidget {
                border: 1px solid lightgrey;
                border-radius: 2px;
                background-color: rgb(255, 255, 255);
                }
            """)

        #endregion

        sectionList = []
        sectionList.append("Rectangle")
        sectionList.append("Diamond")
        sectionList.append("Circle")
        sectionList.append("Box")
        sectionList.append("T-Section")
        sectionList.append("I-Section")

        comboBox = self.ui_window.comboBox
        #comboBox = QtWidgets.QComboBox      #Just to get intellisense working. Gets commented out
        comboBox.setCurrentIndex(0)

        for item in sectionList:
            comboBox.addItem(item)

        comboEvent = comboBoxEvent(self)
        comboBox.currentIndexChanged.connect(comboEvent.getSectionShape)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setStyle('Fusion')
    form = MainForm('./UI designer/testUI.ui')
    sys.exit(app.exec_())

testUI.ui 文件如下所示,位于UI Designer"文件夹中:

testUI.ui file looks like this and is in a folder "UI designer":

<?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>996</width>
    <height>892</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <layout class="QVBoxLayout" name="verticalLayout">
    <item>
     <widget class="QGraphicsView" name="graphicsView">
      <property name="minimumSize">
       <size>
        <width>0</width>
        <height>200</height>
       </size>
      </property>
     </widget>
    </item>
    <item>
     <widget class="Drawer" name="widget" native="true">
      <property name="minimumSize">
       <size>
        <width>0</width>
        <height>250</height>
       </size>
      </property>
      <property name="maximumSize">
       <size>
        <width>16777215</width>
        <height>300</height>
       </size>
      </property>
      <property name="styleSheet">
       <string notr="true"/>
      </property>
     </widget>
    </item>
    <item>
     <widget class="QComboBox" name="comboBox"/>
    </item>
   </layout>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>996</width>
     <height>21</height>
    </rect>
   </property>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <customwidgets>
  <customwidget>
   <class>Drawer</class>
   <extends>QWidget</extends>
   <header>myDrawWidget</header>
   <container>1</container>
  </customwidget>
 </customwidgets>
 <resources/>
 <connections/>
</ui>

调试时 getSectionShape 中的文本字符串为空(期望节类型)但我的索引是正确的.控制台打印一个空白和一个正确的行.getSectionShape 表单 EventMethods.py 中的 self.itemText(index) 无法使用某些内容.任何帮助表示赞赏!

When debugging the text string in getSectionShape is empty (expecting section type) but my index is correct. Console prints one blank and one correct line. Something isn't working with the self.itemText(index) in getSectionShape form EventMethods.py. Any help is appreciated!

推荐答案

self.itemText(index) 在 comboBoxEvent 中意味着什么?当前的 comboBoxEvent 项目.comboBoxEvent 有物品吗? 没有,它是空的,只有窗口中的QComboBox 有物品,comboBoxEvent 不是窗口中的QComboBox.这就解释了为什么你什么也没得到.

What does self.itemText(index) mean in comboBoxEvent? since you are getting the text of the current comboBoxEvent item. Does comboBoxEvent have items? No, it is empty, only the QComboBox that is in the window has the items, comboBoxEvent is not the QComboBox in the window. That explains why you do not get anything.

根据你想要做的有以下几种方法:

According to what you want to do there are the following methods:

1.如果您只想获取 currentText 则使用 currentTextChanged 信号,comboBoxEvent 不必从 QComboBox 继承.

1. If you just want to get the currentText then use the currentTextChanged signal, comboBoxEvent does not have to inherit from a QComboBox.

class comboBoxEvent:
    def getSectionShape(self, text):
        print(text)

# ...
comboBox = self.ui_window.comboBox
comboBox.setCurrentIndex(0)
for item in sectionList:
    comboBox.addItem(item)
self.comboEvent = comboBoxEvent()
comboBox.currentTextChanged.connect(self.comboEvent.getSectionShape)
# ...

2.如果您想在选择新项目时获取 QComboBox 的所有可能信息,那么最好在 getSectionShape 中获取 QComboBox,为此有以下可能性.

2. If you want to get all the possible information of the QComboBox when a new item is selected then it is better to get the QComboBox in getSectionShape, for this there are the following possibilities.

2.1 将 comboBoxEvent 设为 QObject,以便可以使用 slot 中的 sender() 方法获取 QComboBox:

2.1 Make comboBoxEvent a QObject so that the QComboBox can be obtained using the sender() method in the slot:

from PySide2 import QtCore, QtWidgets


class comboBoxEvent(QtCore.QObject):
    @QtCore.Slot()
    def getSectionShape(self):
        obj = self.sender()
        if isinstance(obj, QtWidgets.QComboBox):
            index = obj.currentIndex()
            text = obj.itemText(index)
            print(text)
            print("Index changed to: {}".format(index))

# ...
comboBox = self.ui_window.comboBox
comboBox.setCurrentIndex(0)
for item in sectionList:
    comboBox.addItem(item)
comboEvent = comboBoxEvent(self)
comboBox.currentIndexChanged.connect(comboEvent.getSectionShape)
# ...

2.2通过functools.partial传递QComboBox:

2.2 Pass the QComboBox through functools.partial:

class comboBoxEvent:
    def getSectionShape(self, combo, index):
        index = combo.currentIndex()
        text = combo.itemText(index)
        print(text)
        print("Index changed to: {}".format(index))

from functools import partial

# ...
comboBox = self.ui_window.comboBox
comboBox.setCurrentIndex(0)
for item in sectionList:
    comboBox.addItem(item)
self.comboEvent = comboBoxEvent()
comboBox.currentIndexChanged.connect(partial(self.comboEvent.getSectionShape, comboBox))
# ...

  1. 通过 lambda 传递 QComboBox

class comboBoxEvent:
    def getSectionShape(self, combo):
        index = combo.currentIndex()
        text = combo.itemText(index)
        print(text)
        print("Index changed to: {}".format(index))

# ...
comboBox = self.ui_window.comboBox
comboBox.setCurrentIndex(0)
for item in sectionList:
    comboBox.addItem(item)
self.comboEvent = comboBoxEvent()
comboBox.currentIndexChanged.connect(lambda ix, c= comboBox: self.comboEvent.getSectionShape(c))
# ...

这篇关于在单独的类方法/函数中获取由事件触发的 QComboBox 项目文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆