文章目录
- 1. 状态栏
- 2. 窗口居中显示
- 3. 关闭窗口
- 4. QWidget
- 5. 添加图标
- 6. 气泡提示信息
- 7. QLabel
- 添加快捷键
- 8. QLineEdit
- echoMode
- 验证器
- inputMask
- 综合练习
- 9. QTextEdit
learn from 《PyQt5 快速开发与实战》
1. 状态栏
self.statusbar.showMessage("hello, Michael", 2000)
,第二个参数是显示多长时间ms,默认无限长时间
# -*- coding: utf-8 -*-# Form implementation generated from reading ui file 'D:\gitcode\Python_learning\qt\ch4\status_bar1.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.from PyQt5 import QtCore, QtGui, QtWidgetsclass Ui_MainWindow(object):def setupUi(self, MainWindow):MainWindow.setObjectName("MainWindow")MainWindow.resize(330, 223)self.statusbar = QtWidgets.QStatusBar(MainWindow)self.statusbar.setObjectName("statusbar")MainWindow.setStatusBar(self.statusbar)self.statusbar.showMessage("hello, Michael")self.retranslateUi(MainWindow)QtCore.QMetaObject.connectSlotsByName(MainWindow)def retranslateUi(self, MainWindow):_translate = QtCore.QCoreApplication.translateMainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))if __name__ == "__main__":import sysapp = QtWidgets.QApplication(sys.argv)MainWindow = QtWidgets.QMainWindow()ui = Ui_MainWindow()ui.setupUi(MainWindow)MainWindow.show()sys.exit(app.exec_())
2. 窗口居中显示
class Ui_MainWindow(object):def setupUi(self, MainWindow):MainWindow.setObjectName("MainWindow")MainWindow.resize(330, 223)self.statusbar = QtWidgets.QStatusBar(MainWindow)self.statusbar.setObjectName("statusbar")MainWindow.setStatusBar(self.statusbar)self.statusbar.showMessage("hello, Michael", 2000)MainWindow.setWindowTitle("center_display1")# 居中显示self.center_display(MainWindow)self.retranslateUi(MainWindow)QtCore.QMetaObject.connectSlotsByName(MainWindow)def center_display(self, MainWindow):# 获取屏幕大小screen = QDesktopWidget().screenGeometry() # 获取窗口大小size = MainWindow.geometry()# 移动窗口到中心 即 1/2 的位置MainWindow.move((screen.width() - size.width()) // 2, (screen.height() - size.height()) // 2)
3. 关闭窗口
import time
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QHBoxLayoutclass Ui_MainWindow(QMainWindow):def __init__(self):super(Ui_MainWindow, self).__init__()self.setWindowTitle("michael close window")self.resize(400, 300)self.closeButton = QtWidgets.QPushButton("关闭窗口按钮!!")self.closeButton.setGeometry(QtCore.QRect(110, 190, 91, 31))self.closeButton.setObjectName("closeButton")layout = QHBoxLayout()layout.addWidget(self.closeButton)main_frame = QtWidgets.QWidget()main_frame.setLayout(layout)self.setCentralWidget(main_frame)# 关闭窗口self.closeButton.clicked.connect(self.onClick)def onClick(self):sender = self.sender()print(sender.text() + "被点击了")# 关闭窗口按钮!!被点击了time.sleep(2)self.close()if __name__ == "__main__":import sysapp = QtWidgets.QApplication(sys.argv)win = Ui_MainWindow()win.show()sys.exit(app.exec_())
4. QWidget
QWidget
是最底层的基类
# _*_ coding: utf-8 _*_
# @Time : 2022/5/3 9:45
# @Author : Michael
# @File : screen_geometry1.py
# @desc :
from PyQt5.QtWidgets import QWidget, QDesktopWidget, QApplication, QPushButton
import sysapp = QApplication(sys.argv)
widget = QWidget()
btn = QPushButton('点击我', parent=widget)
btn.move(100, 50)
btn.resize(180, 30)
widget.resize(300, 300)
widget.move(150, 300)
widget.setWindowTitle('我的窗口')
widget.setFixedWidth(300) # 固定宽度widget.show()
print('w.x() = ', widget.x())
print('w.y() = ', widget.y())
print('w.width() = ', widget.width())
print('w.height() = ', widget.height())
print('w.geometry() = ', widget.geometry())
print('w.geometry().x() = ', widget.geometry().x())
print('w.geometry().y() = ', widget.geometry().y())
print('w.geometry().width() = ', widget.geometry().width())
print('w.geometry().height() = ', widget.geometry().height())
print('w.frameGeometry() = ', widget.frameGeometry())
print('w.frameGeometry().x() = ', widget.frameGeometry().x())
print('w.frameGeometry().y() = ', widget.frameGeometry().y())
print('w.frameGeometry().width() = ', widget.frameGeometry().width())
print('w.frameGeometry().height() = ', widget.frameGeometry().height())
print('w.pos() = ', widget.pos())
sys.exit(app.exec_())
w.x() = 150
w.y() = 300
w.width() = 300
w.height() = 300
w.geometry() = PyQt5.QtCore.QRect(151, 331, 300, 300)
w.geometry().x() = 151
w.geometry().y() = 331
w.geometry().width() = 300
w.geometry().height() = 300
w.frameGeometry() = PyQt5.QtCore.QRect(150, 300, 302, 332)
w.frameGeometry().x() = 150
w.frameGeometry().y() = 300
w.frameGeometry().width() = 302
w.frameGeometry().height() = 332
w.pos() = PyQt5.QtCore.QPoint(150, 300)
5. 添加图标
https://www.iconfont.cn
from PyQt5.QtGui import QIcon
widget.setWindowIcon(QIcon('logo.png'))
6. 气泡提示信息
from PyQt5.QtGui import QIcon, QFont
from PyQt5.QtWidgets import QWidget, QDesktopWidget, QApplication, QPushButton, QToolTipQToolTip.setFont(QFont('SansSerif', 10))
widget.setToolTip('这是一个<b>气泡提示</b>')
7. QLabel
# _*_ coding: utf-8 _*_
# @Time : 2022/5/3 13:45
# @Author : Michael
# @File : qlabel1.py
# @desc :
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPalette, QPixmap
from PyQt5.QtWidgets import QWidget, QLabel, QVBoxLayout, QApplicationclass window_qlabel(QWidget):def __init__(self):super().__init__()label1 = QLabel()label2 = QLabel()label3 = QLabel()label4 = QLabel()label1.setText("<font color=red>这是一个红色的文本</font>")label1.setAutoFillBackground(True)palette = QPalette()palette.setColor(QPalette.Window, Qt.blue) # 设置背景色label1.setPalette(palette) # 设置背景色label1.setAlignment(Qt.AlignCenter) # 设置文本对齐方式label1.setTextInteractionFlags(Qt.TextSelectableByMouse) # 设置文本可选label2.setText("<a href='#'>michael 学习 PyQt</a>")label2.linkActivated.connect(self.link_clicked) # 连接鼠标点击信号label4.setText("<a href='http://michael.blog.csdn.net'>michael的博客</a>")label4.setOpenExternalLinks(True) # 设置打开外部链接label4.setToolTip("欢迎访问!") # 设置鼠标悬停提示label4.linkHovered.connect(self.link_hovered) # 连接鼠标悬停信号label3.setAlignment(Qt.AlignCenter) # 设置文本对齐方式label3.setToolTip('提示:这是一张图片哦') # 设置鼠标悬停提示label3.setPixmap(QPixmap('logo.png')) # 设置图片vbox = QVBoxLayout()vbox.addWidget(label1)vbox.addStretch()vbox.addWidget(label2)vbox.addStretch()vbox.addWidget(label3)vbox.addStretch()vbox.addWidget(label4)self.setLayout(vbox)self.setWindowTitle("QLabel 示例")def link_hovered(self):print("鼠标悬停")def link_clicked(self):print("鼠标点击")if __name__ == '__main__':import sysapp = QApplication(sys.argv)win = window_qlabel()win.show()sys.exit(app.exec_())
添加快捷键
# _*_ coding: utf-8 _*_
# @Time : 2022/5/4 9:10
# @Author : Michael
# @File : qlabel_hotkey1.py
# @desc :import sys
from PyQt5.QtWidgets import QWidget, QLabel, QApplication, QDialog, QLineEdit, QPushButton, QGridLayoutclass Qlabel_hotkey1(QDialog):def __init__(self):super().__init__()self.setWindowTitle("QLabel_hotkey1 demo")nameLabel1 = QLabel("&Name") # 必须加& 否则不能绑定快捷键nameLineEdit1 = QLineEdit()nameLabel1.setBuddy(nameLineEdit1) # 设置名称标签和输入框的关联nameLabel2 = QLabel("&Password")nameLineEdit2 = QLineEdit()nameLabel2.setBuddy(nameLineEdit2)submit_btn = QPushButton("&Submit")cancel_btn = QPushButton("&Cancel")layout = QGridLayout(self)layout.addWidget(nameLabel1, 0, 0)layout.addWidget(nameLineEdit1, 0, 1, 1, 2)layout.addWidget(nameLabel2, 1, 0)layout.addWidget(nameLineEdit2, 1, 1, 1, 2)layout.addWidget(submit_btn, 2, 1)layout.addWidget(cancel_btn, 2, 2)if __name__ == "__main__":app = QApplication(sys.argv)w = Qlabel_hotkey1()w.show()sys.exit(app.exec_())
使用 alt + 绑定的首字母(N、P、S、C)进行切换
8. QLineEdit
- 单行文本框,多行使用
QTextEdit
常用的信号:
selectionChanged
选择改变了,就发射信号textChanged
修改文本内容时editingFinished
编辑文本结束时
echoMode
# _*_ coding: utf-8 _*_
# @Time : 2022/5/4 14:26
# @Author : Michael
# @File : line_edit1.py
# @desc :from PyQt5.QtWidgets import QApplication, QWidget, QLineEdit, QLabel, QFormLayout
import sysclass lineEditDemo(QWidget):def __init__(self):super().__init__()self.setWindowTitle("lineEditDemo")layout = QFormLayout()normalLineEdit = QLineEdit()noEchoLineEdit = QLineEdit()passwordLineEdit = QLineEdit()passwordEchoOnEditLineEdit = QLineEdit()layout.addRow("Normal LineEdit", normalLineEdit)layout.addRow("No Echo LineEdit", noEchoLineEdit)layout.addRow("Password LineEdit", passwordLineEdit)layout.addRow("Password Echo On Edit LineEdit", passwordEchoOnEditLineEdit)normalLineEdit.setPlaceholderText("Normal LineEdit")noEchoLineEdit.setPlaceholderText("No Echo LineEdit")passwordLineEdit.setPlaceholderText("Password LineEdit")passwordEchoOnEditLineEdit.setPlaceholderText("Password Echo On Edit LineEdit")normalLineEdit.setEchoMode(QLineEdit.Normal)noEchoLineEdit.setEchoMode(QLineEdit.NoEcho)passwordLineEdit.setEchoMode(QLineEdit.Password)passwordEchoOnEditLineEdit.setEchoMode(QLineEdit.PasswordEchoOnEdit)self.setLayout(layout)
if __name__=='__main__':app = QApplication(sys.argv)main = lineEditDemo()main.show()sys.exit(app.exec_())
验证器
# _*_ coding: utf-8 _*_
# @Time : 2022/5/4 15:23
# @Author : Michael
# @File : validator1.py
# @desc :
from PyQt5.QtCore import QRegExp
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QPushButton, QHBoxLayout, QVBoxLayout, QFormLayout
from PyQt5.QtGui import QIntValidator, QDoubleValidator, QRegExpValidator
import sysclass lineEditDemo1(QWidget):def __init__(self):super().__init__()self.setWindowTitle('lineEditDemo1 验证器')layout = QFormLayout()intLineEdit = QLineEdit()doubleLineEdit = QLineEdit()validatorLineEdit = QLineEdit()layout.addRow('整数', intLineEdit)layout.addRow('浮点数', doubleLineEdit)layout.addRow('字母和数字', validatorLineEdit)intLineEdit.setPlaceholderText('整数')doubleLineEdit.setPlaceholderText('浮点数')validatorLineEdit.setPlaceholderText('字母和数字')intValidator = QIntValidator(self)intValidator.setRange(1,99)doubleValidator = QDoubleValidator(self)doubleValidator.setRange(-100, 100)doubleValidator.setNotation(QDoubleValidator.StandardNotation)doubleValidator.setDecimals(2)regValidator = QRegExpValidator(QRegExp('[a-zA-Z0-9]+$'), self)intLineEdit.setValidator(intValidator)doubleLineEdit.setValidator(doubleValidator)validatorLineEdit.setValidator(regValidator)self.setLayout(layout)if __name__ == '__main__':app = QApplication(sys.argv)main = lineEditDemo1()main.show()sys.exit(app.exec_())
inputMask
# _*_ coding: utf-8 _*_
# @Time : 2022/5/4 15:48
# @Author : Michael
# @File : inputMask1.py
# @desc :
from PyQt5.QtWidgets import QWidget, QFormLayout, QLineEditclass inputmask(QWidget):def __init__(self):super().__init__()self.setWindowTitle("输入掩码")layout = QFormLayout()ip_lineEdit = QLineEdit()mac_lineEdit = QLineEdit()date_lineEdit = QLineEdit()licence_lineEdit = QLineEdit()ip_lineEdit.setInputMask("000.000.000.000;_")mac_lineEdit.setInputMask("HH:HH:HH:HH:HH:HH;_")date_lineEdit.setInputMask("0000-00-00")licence_lineEdit.setInputMask(">AAAAA-AAAAA-AAAAA-AAAAA-AAAAA;#")layout.addRow("IP地址", ip_lineEdit)layout.addRow("MAC地址", mac_lineEdit)layout.addRow("日期", date_lineEdit)layout.addRow("许可证", licence_lineEdit)self.setLayout(layout)if __name__ == '__main__':import sysfrom PyQt5.QtWidgets import QApplicationapp = QApplication(sys.argv)win = inputmask()win.show()sys.exit(app.exec_())
综合练习
# _*_ coding: utf-8 _*_
# @Time : 2022/5/4 16:22
# @Author : Michael
# @File : text_example.py
# @desc :
from PyQt5.QtGui import QIntValidator, QFont, QDoubleValidator
from PyQt5.QtWidgets import QWidget, QLineEdit, QFormLayout
from PyQt5.QtCore import Qtclass lineEdit_demo(QWidget):def __init__(self):super(lineEdit_demo, self).__init__()e1 = QLineEdit()e1.setValidator(QIntValidator())e1.setMaxLength(4)e1.setAlignment(Qt.AlignRight)e1.setFont(QFont("Arial", 20))e2 = QLineEdit()e2.setValidator(QDoubleValidator(0.99, 99.99, 2))layout = QFormLayout()layout.addRow("整数验证器", e1)layout.addRow("浮点数验证器", e2)e3 = QLineEdit()e3.setInputMask("+99_9999_999999")layout.addRow("输入掩码", e3)e4 = QLineEdit()e4.textChanged.connect(self.text_changed)layout.addRow("文本改变", e4)e5 = QLineEdit()e5.setEchoMode(QLineEdit.Password)e5.editingFinished.connect(self.enterPress)layout.addRow("密码模式", e5)e6 = QLineEdit("Hello world, michael")e6.setReadOnly(True)layout.addRow("只读", e6)self.setLayout(layout)self.setWindowTitle("QLineEdit控件")def text_changed(self, text):print('输入的内容:', text)def enterPress(self):print("已输入内容")if __name__ == '__main__':import sysfrom PyQt5.QtWidgets import QApplicationapp = QApplication(sys.argv)main = lineEdit_demo()main.show()sys.exit(app.exec_())
9. QTextEdit
- 多行文本,超出显示范围可以显示水平或者垂直滚动条,还可以显示 HTML
# _*_ coding: utf-8 _*_
# @Time : 2022/5/4 19:24
# @Author : Michael
# @File : text_edit1.py
# @desc :
from PyQt5.QtWidgets import QWidget, QTextEdit, QPushButton, QVBoxLayout, QApplicationclass textEdit1(QWidget):def __init__(self):super().__init__()self.setWindowTitle('多行文本例子')self.resize(300, 200)self.textEdit = QTextEdit()self.btn1 = QPushButton('显示文本')self.btn2 = QPushButton('显示HTML')self.btn1.clicked.connect(self.btn1_clicked)self.btn2.clicked.connect(self.btn2_clicked)layout = QVBoxLayout()layout.addWidget(self.textEdit)layout.addWidget(self.btn1)layout.addWidget(self.btn2)self.setLayout(layout)def btn1_clicked(self):self.textEdit.setPlainText('Hello Michael!')def btn2_clicked(self):self.textEdit.setHtml("<font color='red' size='10'>Hello Michael!<br>点击按钮</font><br><br><br><br><a href='https://michael.blog.csdn.net/'>访问我的博客</a>")if __name__ == '__main__':import sysapp = QApplication(sys.argv)ui = textEdit1()ui.show()sys.exit(app.exec_())