PYQT Qcombobox set value selected to a variable

2020-04-30 02:25发布

I have a combox, and want to add the vaue selected in the box to a variable. The variable. I tried a few things from the documentation and was only successful on setting it to a Qlabel. Any help please

     self.languageLbl = QtGui.QLabel("Download_IVR", self)
     comboBox = QtGui.QComboBox(self)
     comboBox.addItem("IVR_ITALY")
     comboBox.addItem("IVR_FRANCE")
     comboBox.addItem("IVR_SPAIN")
     comboBox.addItem("IVR_GERMANY")
     comboBox.move(650, 250)
     comboBox.resize(150,40)
     self.languageLbl.move(650,150)
     comboBox.activated[str].connect(self.languageChoice)

 def download_button(self):

     ivrLang = self.comboBox.currentText()

I want to set ivrLang to the item selected in the combobox. Thanks!

标签: python pyqt
2条回答
▲ chillily
2楼-- · 2020-04-30 02:33

I ended up setting ivrLang to a Qlabel. So as the QLabel is displayed, the variable is set to the text of the QLabel. That way I get the Label, and variable at the same time. Perhaps maybe not the best way to do it, but it works

    def languageChoice(self, text):

        self.languageLbl.setText(text)
    def download_button(self, text):
        directoryUser = self.directory
        ivrNum = self.lblNumber.text()
        username = self.userName.text()

        ivrLang = self.languageLbl.text()
查看更多
Explosion°爆炸
3楼-- · 2020-04-30 02:54

You aren't connecting your signal to your callback function. You need:

self.combobox.activated[str].connect(self.download_button)

And download button should look like:

def download_button(self, text):
    irvLang = text

Note that you still haven't done anything with that variable irvLang.

Also it would be wise to make the comboBox and attribute of your class using self:

self.comboBox = QtGui.QComboBox(self)

EDIT: Here is a complete example that does what you seem to want.

from PyQt4 import QtGui

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.cb = QtGui.QComboBox(self)
        self.cb.addItem("One")
        self.cb.addItem("Two")
        self.cb.activated[str].connect(self.selected)

    def selected(self, text):
        self.selected_text = text
        print(self.selected_text)

app = QtGui.QApplication([])
mw = MainWindow()
mw.show()
app.exec_()
查看更多
登录 后发表回答