[ PyQt入門教程 ] PyQt5基本控件使用:單選按鈕、複選框、下拉框、文本框

  • 2019 年 10 月 3 日
  • 筆記

   本文主要介紹PyQt5界面最基本使用的單選按鈕、複選框、下拉框三種控件的使用方法進行介紹。

   1、RadioButton單選按鈕/CheckBox複選框。需要知道如何判斷單選按鈕是否被選中。

   2、ComboBox下拉框。需要知道如何對下拉框中的取值進行設置以及代碼實現中如何獲取用戶選中的值。

   帶着這些問題下面開始介紹這RadioButton單選按鈕、CheckBox複選框、ComboBox下拉框三種基本控件的使用方法

QRadioButton單選按鈕

  單選按鈕為用戶提供多選一的選擇,是一種開關按鈕。QRadioButton單選按鈕是否選擇狀態通過isChecked()方法判斷。isChecked()方法返回值True表示選中,False表示未選中。

RadioButton示例完整代碼如下:

# -*- coding: utf-8 -*-    import sys  from PyQt5 import QtCore, QtGui, QtWidgets  from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox, QRadioButton    class Ui_Form(object):      def setupUi(self, Form):          Form.setObjectName("Form")          Form.resize(309, 126)          self.radioButton = QtWidgets.QRadioButton(Form)          self.radioButton.setGeometry(QtCore.QRect(70, 40, 89, 16))          self.radioButton.setObjectName("radioButton")          self.okButton = QtWidgets.QPushButton(Form)          self.okButton.setGeometry(QtCore.QRect(70, 70, 75, 23))          self.okButton.setObjectName("okButton")            self.retranslateUi(Form)          QtCore.QMetaObject.connectSlotsByName(Form)        def retranslateUi(self, Form):          _translate = QtCore.QCoreApplication.translate          Form.setWindowTitle(_translate("Form", "RadioButton單選按鈕例子"))          self.radioButton.setText(_translate("Form", "單選按鈕"))          self.okButton.setText(_translate("Form", "確定"))    class MyMainForm(QMainWindow, Ui_Form):      def __init__(self, parent=None):          super(MyMainForm, self).__init__(parent)          self.setupUi(self)          self.okButton.clicked.connect(self.checkRadioButton)        def checkRadioButton(self):          if self.radioButton.isChecked():              QMessageBox.information(self,"消息框標題","我RadioButton按鈕被選中啦!",QMessageBox.Yes | QMessageBox.No)    if __name__ == "__main__":      app = QApplication(sys.argv)      myWin = MyMainForm()      myWin.show()      sys.exit(app.exec_())

運行結果如下:

 關鍵代碼介紹:

  self.radioButton.isChecked()  –> 用於判斷RadioButton控件是否被選中。返回值Trule表示按鈕被選中,False表示按鈕未選中。

QCheckBox複選框

   複選框和單選按鈕一樣都是選項按鈕,區別是複選框為用戶提供多選多的選擇。複選框按鈕同樣是使用isChecked()方法判斷是否被選中。

CheckBox例子完整代碼如下:

# -*- coding: utf-8 -*-    import sys  from PyQt5 import QtCore, QtGui, QtWidgets  from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox, QCheckBox    class Ui_Form(object):      def setupUi(self, Form):          Form.setObjectName("Form")          Form.resize(380, 154)          self.freshcheckBox = QtWidgets.QCheckBox(Form)          self.freshcheckBox.setGeometry(QtCore.QRect(50, 40, 71, 31))          font = QtGui.QFont()          font.setPointSize(14)          self.freshcheckBox.setFont(font)          self.freshcheckBox.setObjectName("freshcheckBox")          self.bearcheckBox = QtWidgets.QCheckBox(Form)          self.bearcheckBox.setGeometry(QtCore.QRect(140, 40, 71, 31))          font = QtGui.QFont()          font.setPointSize(14)          self.bearcheckBox.setFont(font)          self.bearcheckBox.setObjectName("bearcheckBox")          self.okButton = QtWidgets.QPushButton(Form)          self.okButton.setGeometry(QtCore.QRect(230, 40, 71, 31))          font = QtGui.QFont()          font.setPointSize(14)          self.okButton.setFont(font)          self.okButton.setObjectName("okButton")            self.retranslateUi(Form)          QtCore.QMetaObject.connectSlotsByName(Form)        def retranslateUi(self, Form):          _translate = QtCore.QCoreApplication.translate          Form.setWindowTitle(_translate("Form", "CheckBox例子"))          self.freshcheckBox.setText(_translate("Form", ""))          self.bearcheckBox.setText(_translate("Form", "熊掌"))          self.okButton.setText(_translate("Form", "確定"))    class MyMainForm(QMainWindow, Ui_Form):      def __init__(self, parent=None):          super(MyMainForm, self).__init__(parent)          self.setupUi(self)          self.okButton.clicked.connect(self.checkCheckBox)        def checkCheckBox(self):          if self.freshcheckBox.isChecked() and self.bearcheckBox.isChecked():              QMessageBox.information(self,"消息框標題","魚和熊掌我要兼得!",QMessageBox.Yes | QMessageBox.No)    if __name__ == "__main__":      app = QApplication(sys.argv)      myWin = MyMainForm()      myWin.show()      sys.exit(app.exec_())

運行結果如下:

 關鍵代碼介紹:

  self.freshcheckBox.isChecked() and self.bearcheckBox.isChecked()  –> 同樣適用isChecked()函數判斷。

QComboBox下拉列表框

  下拉列表框是一個集按鈕和下拉選項於一體的控件。通常用於固定的枚舉值供用戶選擇時使用。對於下拉列表框的使用最基本的是要知道如何添加下拉列表框中的值以及如何獲取下拉框中選擇的值。

  (1)如何添加下拉列表框中的值。

  1、使用addItem() 添加一個下拉選項或者additems() 從列表中添加下拉選項 方法進行添加。

  2、如果使用Qt Designer畫圖實現,可以將ComboBox控件添加到主界面後雙擊下拉列表框進行打開添加。如下:

  (2)如何獲取下拉框中的取值

  使用函數currentText() 返回選項中的文本進行獲取

ComboBox示例完整代碼如下:

# -*- coding: utf-8 -*-    import sys  from PyQt5 import QtCore, QtGui, QtWidgets  from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox, QComboBox    class Ui_Form(object):      def setupUi(self, Form):          Form.setObjectName("Form")          Form.resize(400, 130)          self.comboBox = QtWidgets.QComboBox(Form)          self.comboBox.setGeometry(QtCore.QRect(80, 50, 69, 22))          self.comboBox.setObjectName("comboBox")          self.comboBox.addItem("")          self.comboBox.addItem("")          self.comboBox.addItem("")          self.comboBox.addItem("")          self.okButton = QtWidgets.QPushButton(Form)          self.okButton.setGeometry(QtCore.QRect(190, 50, 75, 23))          self.okButton.setObjectName("okButton")            self.retranslateUi(Form)          QtCore.QMetaObject.connectSlotsByName(Form)        def retranslateUi(self, Form):          _translate = QtCore.QCoreApplication.translate          Form.setWindowTitle(_translate("Form", "ComboBox下拉框例子"))          self.comboBox.setItemText(0, _translate("Form", "Python"))          self.comboBox.setItemText(1, _translate("Form", "C++"))          self.comboBox.setItemText(2, _translate("Form", "Go"))          self.comboBox.setItemText(3, _translate("Form", "Java"))          self.okButton.setText(_translate("Form", "確定"))    class MyMainForm(QMainWindow, Ui_Form):      def __init__(self, parent=None):          super(MyMainForm, self).__init__(parent)          self.setupUi(self)          self.okButton.clicked.connect(self.getComboxBoxValue)        def getComboxBoxValue(self):          select_value = self.comboBox.currentText()          QMessageBox.information(self,"消息框標題","你要學%s,為師給你說道說道!" % (select_value,),QMessageBox.Yes | QMessageBox.No)    if __name__ == "__main__":      app = QApplication(sys.argv)      myWin = MyMainForm()      myWin.show()      sys.exit(app.exec_())

運行結果如下:

 關鍵代碼介紹:

  select_value = self.comboBox.currentText() –> 使用currentText()函數獲取下拉框中選擇的值

文本框控件(QLineEdit、QTextEdit)

  文本框控件分為單行文本框(QLineEdit)和多行文本框(QTextEdit)。單行文本框只允許輸入一行字符串。多行文本框可以顯示多行文本內容,當文本內容超出控件顯示範圍時,可以顯示水平和垂直滾動條。

  針對文本框控件,這裡主要了解文本框內容的設置、獲取以及清除三種主要方法。單行文本框和多行文本框的設置和獲取方法不同,如下。

  單行文本框(QLineEdit)方法如下:

  setText():設置單行文本框內容。

  Text():返迴文本框內容

  clear():清除文本框內容

  多行文本框(QTextEdit)方法如下:

  setPlainText():設置多行文本框的文本內容。

  toPlainText():獲取多行文本框的文本內容。

  clear():清除多行文本框的內容

文本框使用實例如下:

 

# -*- coding: utf-8 -*-    import sys  from PyQt5 import QtCore, QtGui, QtWidgets  from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox, QComboBox    class Ui_Form(object):      def setupUi(self, Form):          Form.setObjectName("Form")          Form.resize(411, 314)          self.lineEdit = QtWidgets.QLineEdit(Form)          self.lineEdit.setGeometry(QtCore.QRect(120, 50, 251, 41))          self.lineEdit.setObjectName("lineEdit")          self.lineedit_label = QtWidgets.QLabel(Form)          self.lineedit_label.setGeometry(QtCore.QRect(10, 60, 81, 20))          font = QtGui.QFont()          font.setPointSize(11)          font.setBold(True)          font.setWeight(75)          self.lineedit_label.setFont(font)          self.lineedit_label.setObjectName("lineedit_label")          self.textEdit = QtWidgets.QTextEdit(Form)          self.textEdit.setGeometry(QtCore.QRect(120, 120, 251, 141))          self.textEdit.setObjectName("textEdit")          self.textedit_label = QtWidgets.QLabel(Form)          self.textedit_label.setGeometry(QtCore.QRect(13, 180, 81, 31))          font = QtGui.QFont()          font.setPointSize(11)          font.setBold(True)          font.setWeight(75)          self.textedit_label.setFont(font)          self.textedit_label.setObjectName("textedit_label")          self.run_Button = QtWidgets.QPushButton(Form)          self.run_Button.setGeometry(QtCore.QRect(150, 280, 91, 31))          font = QtGui.QFont()          font.setPointSize(11)          font.setBold(True)          font.setWeight(75)          self.run_Button.setFont(font)          self.run_Button.setObjectName("run_Button")            self.retranslateUi(Form)          QtCore.QMetaObject.connectSlotsByName(Form)        def retranslateUi(self, Form):          _translate = QtCore.QCoreApplication.translate          Form.setWindowTitle(_translate("Form", "TextEdit_Example"))          self.lineedit_label.setText(_translate("Form", "LineEdit"))          self.textedit_label.setText(_translate("Form", "TextEdit"))          self.run_Button.setText(_translate("Form", "Run"))    class MyMainForm(QMainWindow, Ui_Form):      def __init__(self, parent=None):          super(MyMainForm, self).__init__(parent)          self.setupUi(self)          self.run_Button.clicked.connect(self.set_display_edit)        def set_display_edit(self):          #設置前先清除文本內容          self.lineEdit.clear()          self.textEdit.clear()            #設置文本框內容          self.lineEdit.setText("Lineedit contents")          self.textEdit.setPlainText("Textedit contents")            #獲取文本框內容,並彈框顯示內容          str1 = self.lineEdit.text()          str2 = self.textEdit.toPlainText()          QMessageBox.information(self,"獲取信息","LineEdit文本框內容為:%s,TextEdit文本框內容為:%s" %(str1,str2))      if __name__ == "__main__":      app = QApplication(sys.argv)      myWin = MyMainForm()      myWin.show()      sys.exit(app.exec_())

 

運行結果如下:

 

 關鍵代碼如下:

    def set_display_edit(self):          #設置前先清除文本內容          self.lineEdit.clear()          self.textEdit.clear()            #設置文本框內容          self.lineEdit.setText("Lineedit contents")          self.textEdit.setPlainText("Textedit contents")            #獲取文本框內容,並彈框顯示內容          str1 = self.lineEdit.text()          str2 = self.textEdit.toPlainText()          QMessageBox.information(self,"獲取信息","LineEdit文本框內容為:%s,TextEdit文本框內容為:%s" %(str1,str2))

小結

  RadioButton單選按鈕、CheckBox複選框、ComboBox下拉框三種基本控件的使用方法介紹完了。本文中的內容和實例也基本回答了開篇提到的問題。這三種基本控件的使用簡單但也很頻繁。可以多動手實踐一下。上文中的程序都可以直接運行。可以運行看看效果。