Bharath Kumar
Bharath Kumar

Reputation: 317

How to take input from ComboBox in PyQt4

I have created a combobox in PyQt4. This combobox will have 5 options and the user needs to select one option among it and click the submit button. I have tried to define a function called printing action to be used after the user clicks the submit button

def home(self):

    self.lbl = QtGui.QLabel('Types of Analysis', self)
    self.lbl.setFont(QtGui.QFont('SansSerif', 15))
    btn = QtGui.QPushButton('Submit', self)
    btn.move(200, 200)
    cb = QtGui.QComboBox(self)
    btn = QtGui.QPushButton('Submit', self)
    cb.addItem('Sentiment Analysis')
    cb.addItem('Data Cleansing')
    cb.addItem('Genomics')
    cb.addItem('Integration')
    cb.addItem('Visualization')
    cb.move(200,100)
    cb.resize(150,40)
    QtGui.QApplication.setStyle(QtGui.QStyleFactory.create('Cleanlooks'))
    cb.activated[str].connect(self.onactivate)
    btn.clicked.connect(self.printingaction)
    self.show()

def printingaction(self):
    print(t)

Can you help me in understanding how to take the input after the user has selected one among the given options and presses the submit button

Upvotes: 1

Views: 2546

Answers (1)

Green Cell
Green Cell

Reputation: 4783

Here's an example where it will print the comboBox's current text and index:

import sys
from PyQt4 import QtGui, QtCore

class MyWindow(QtGui.QWidget):
    def __init__(self, parent = None):
        super(MyWindow, self).__init__(parent)

        # Create controls
        self.lbl = QtGui.QLabel('Types of Analysis', self)
        self.lbl.setFont(QtGui.QFont('SansSerif', 15) )
        self.cb = QtGui.QComboBox(self)
        self.cb.addItems(['Sentiment Analysis', 'Data Cleansing', 'Genomics', 'Integration', 'Visualization'])
        self.btn = QtGui.QPushButton('Submit', self)
        self.btn.clicked.connect(self.printingaction)

        # Create layout
        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addWidget(self.lbl)
        mainLayout.addWidget(self.cb)
        mainLayout.addWidget(self.btn)
        self.setLayout(mainLayout)

        self.show()

    def printingaction(self):
        print 'Current item: {0}'.format( self.cb.currentIndex() ) # ComboBox's index
        print 'Current index: {0}'.format( self.cb.currentText() ) # ComboBox's text

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    win = MyWindow()
    sys.exit( app.exec_() )

Upvotes: 2

Related Questions