QtGui.QComboBox

The QtGui.QComboBox is a widget that allows a user to choose from a list of options.

#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode PyQt4 tutorial 

This example shows
how to use QtGui.QComboBox widget.
 
author: Jan Bodnar
website: zetcode.com 
last edited: September 2011
"""

import sys
from PyQt4 import QtGui, QtCore

class Example(QtGui.QWidget):
    
    def __init__(self):
        super(Example, self).__init__()
        
        self.initUI()
        
    def initUI(self):      

        self.lbl = QtGui.QLabel("Ubuntu", self)

        combo = QtGui.QComboBox(self)
        combo.addItem("Ubuntu")
        combo.addItem("Mandriva")
        combo.addItem("Fedora")
        combo.addItem("Red Hat")
        combo.addItem("Gentoo")

        combo.move(50, 50)
        self.lbl.move(50, 150)

        combo.activated[str].connect(self.onActivated)        
         
        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('QtGui.QComboBox')
        self.show()
        
    def onActivated(self, text):
      
        self.lbl.setText(text)
        self.lbl.adjustSize()  
                
def main():
    
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

The example shows a QtGui.QComboBox and a QtGui.QLabel. The combo box has a list of five options. These are the names of Linux distros. The label widget displays the selected option from the combo box.

combo = QtGui.QComboBox(self)
combo.addItem("Ubuntu")
combo.addItem("Mandriva")
combo.addItem("Fedora")
combo.addItem("Red Hat")
combo.addItem("Gentoo")

We create a QtGui.QComboBox widget with five options.

combo.activated[str].connect(self.onActivated) 

Upon an item selection, we call the onActivated() method.

def onActivated(self, text):
  
    self.lbl.setText(text)
    self.lbl.adjustSize() 

Inside the method, we set the text of the chosen item to the label widget. We adjust the size of the label.

QtGui.QComboBoxFigure: QtGui.QComboBox

原文地址:https://www.cnblogs.com/hushaojun/p/4435874.html