样式

  1. widget = QLabel("Hello")
  2. font = widget.font()
  3. font.setPointSize(30)
  4. widget.setFont(font)
  5. # 文字组件垂直居中且水平居中,可选项有AlignTop,AlignBottom,AlignLeft,
  6. # AlignRight, AlignJustify,AlignCenter
  7. widget.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
  8. self.setCentralWidget(widget)

组件一览

  1. from PyQt5.QtWidgets import(
  2. QCheckBox,QComboBox,QDateEdit,QDateTimeEdit,
  3. QDial,QDoubleSpinBox,QFontComboBox,QLCDNumber,
  4. QLabel,QLineEdit,QProgressBar,QPushButton,
  5. QRadioButton,QSlider,QSpinBox, QTimeEdit,
  6. QVBoxLayout,QWidget,QMainWindow,QApplication,
  7. QLabel,
  8. )
  9. from PyQt5.QtCore import Qt
  10. import sys
  11. class MainWindow(QMainWindow):
  12. def __init__(self):
  13. super().__init__()
  14. self.setWindowTitle("教学应用")
  15. layout = QVBoxLayout()
  16. widgets = [
  17. # 勾选
  18. QCheckBox,
  19. # 下拉列表框
  20. QComboBox,
  21. # 日期输入框
  22. QDateEdit,
  23. # 时间输入框
  24. QDateTimeEdit,
  25. QDial,
  26. # 双精度输入框
  27. QDoubleSpinBox,
  28. # 文字选项栏
  29. QFontComboBox,
  30. # 非交互式标签
  31. QLabel,
  32. # 输入框
  33. QLineEdit,
  34. # 进度条
  35. QProgressBar,
  36. # 按钮
  37. QPushButton,
  38. # 单项
  39. QRadioButton,
  40. # 滑块条
  41. QSlider,
  42. # 整数框
  43. QSpinBox,
  44. # 时间输入框
  45. QTimeEdit,
  46. ]
  47. for w in widgets:
  48. layout.addWidget(w())
  49. # 实例化一个widget
  50. widget = QWidget()
  51. # 将layout填入
  52. widget.setLayout(layout)
  53. self.setCentralWidget(widget)
  54. if __name__ == "__main__":
  55. app =QApplication(sys.argv)
  56. window = MainWindow()
  57. window.show()
  58. app.exec()

3. 组件 - 图1

下拉框的设置

  1. selectCom = QComboBox()
  2. # 添加选项
  3. selectCom.addItems(["卡布奇洛","拿铁","美式"] )
  4. # 监听索引值变动
  5. selectCom.currentIndexChanged.connect(self.index_changed)
  6. # 监听文本变动
  7. selectCom.currentTextChanged.connect(self.text_changed)
  8. # 下拉框具有输入功能
  9. selectCom.setEditable(True)
  10. # 设置选项最大长度
  11. selectCom.setMaxCount(10)
  12. self.setCentralWidget(selectCom)
  13. def index_changed(self,i):
  14. print(i)
  15. def text_changed(self,t):
  16. print(t)

3. 组件 - 图2

输入框

  1. inputCom = QLineEdit()
  2. # 设置输入框值最大长度
  3. inputCom.setMaxLength(20)
  4. # 提示文
  5. inputCom.setPlaceholderText("请输入您的名字")
  6. # 监听文本变动
  7. inputCom.textChanged.connect(self.text_changed)
  8. # 监听编辑变动
  9. inputCom.textEdited.connect(self.text_edited)
  10. # 监听回车键,注意这个监听不传输入框中的值
  11. inputCom.returnPressed.connect(self.return_pressed)
  12. self.setCentralWidget(inputCom)
  13. def text_edited(self,i):
  14. print(i)
  15. def text_changed(self,t):
  16. print(t)
  17. def return_pressed(self):
  18. # 修改输入框中的值
  19. self.centralWidget().setText("Boom")

勾选框

  1. checkBox = QCheckBox()
  2. # 设置勾选的初始状态
  3. checkBox.setCheckState(Qt.Unchecked)
  4. checkBox.stateChanged.connect(self.show_state)
  5. self.setCentralWidget(checkBox)
  6. def show_state(self,s):
  7. print(s == Qt.Checked)