45

Using pyqt4 and python 2.6, I am using a qcombobox to provide a list of options. I am having problems with using the selected option. I have been able to use a signal to trigger a method when the option is selected, but the problem is that when the user clicks run, the contents of several of these comboboxes need to be taken into account. So basically I need to get the selected contents of a combobox as a string. Thus far I have only been able use this:

print combobox1.currentText()

to get this:

PyQt4.QtCore.QString(u'Test Selection2')

when all I really want is the 'Test Selection' bit, any ideas? My combo box was made like this:

combobox1 = qt.QComboBox()
combobox1.addItems(['Test Selection1', 'Test Selection2'])
mainLayout.addWidget(combobox1, 0, 0)
Ben
  • 5,525
  • 8
  • 42
  • 66

4 Answers4

92

You can convert the QString type to python string by just using the str function. Assuming you are not using any Unicode characters you can get a python string as below:

text = str(combobox1.currentText())

If you are using any unicode characters, you can do:

text = unicode(combobox1.currentText())
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
sateesh
  • 27,947
  • 7
  • 36
  • 45
  • thats perfect! that did exactly what i needed to do. I am now looking at changing the selected item in a combobox without having to click it. i have tried .setItemText("text choice") but that gives me the following error: TypeError: QComboBox.setItemText(int, QString): argument 1 has unexpected type 'str' I do not know what type it was expecting or even if this is the best way to go about it. I will only need to change the selected item to one of the options in the list. – Ben May 24 '11 at 16:55
  • The first argument for the setItemText is the index of item in the QComboBox whose value you want to change. Take a look at Qt documentation http://doc.qt.nokia.com/4.7-snapshot/qcombobox.html#setItemText. You need to refer to the API docs to write to familiarize with the methods available, their signatutre etc. – sateesh May 24 '11 at 17:26
4

PyQt4 can be forced to use a new API in which QString is automatically converted to and from a Python object:

import sip
sip.setapi('QString', 2)

With this API, QtCore.QString class is no longer available and self.ui.comboBox.currentText() will return a Python string or unicode object.

See Selecting Incompatible APIs from the doc.

Frodon
  • 3,684
  • 1
  • 16
  • 33
4

Getting the Text of ComboBox when the item is changed

     self.ui.comboBox.activated.connect(self.pass_Net_Adap)

  def pass_Net_Adap(self):
      print str(self.ui.comboBox.currentText())
Cholavendhan
  • 337
  • 1
  • 5
  • 11
-1

If you want the text value of a QString object you can use the __str__ property, like this:

>>> a = QtCore.QString("Happy Happy, Joy Joy!")
>>> a
PyQt4.QtCore.QString(u'Happy Happy, Joy Joy!')
>>> a.__str__()
u'Happy Happy, Joy Joy!'

Hope that helps.

Raceyman
  • 1,354
  • 1
  • 9
  • 12