Qpushbutton基本操作
1.热键
2.按钮加图标
3.按钮事件等
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
layout = QVBoxLayout()
self.btn1 = QPushButton("Button1")
self.btn1.setCheckable(True)
self.btn1.toggle()
self.btn1.clicked.connect(lambda:self.whichbtn(self.btn1) )
self.btn1.clicked.connect(self.btnstate)
layout.addWidget(self.btn1)
self.btn2 = QPushButton('image')
self.btn2.setIcon(QIcon(QPixmap(r'./resource/github.png')))
self.btn2.clicked.connect(lambda:self.whichbtn(self.btn2) )
layout.addWidget(self.btn2)
self.setLayout(layout)
self.btn3 = QPushButton("Disabled")
self.btn3.setEnabled(False)
layout.addWidget(self.btn3)
self.btn4= QPushButton("&Download")
self.btn4.setDefault(True)
self.btn4.clicked.connect(lambda:self.whichbtn(self.btn4))
layout.addWidget(self.btn4)
self.setWindowTitle("Button demo")
def btnstate(self):
if self.btn1.isChecked():
print("button pressed" )
else:
print("button released" )
def whichbtn(self,btn):
print("clicked button is " + btn.text() )
if __name__ == '__main__':
app = QApplication(sys.argv)
btnDemo = Form()
btnDemo.show()
sys.exit(app.exec_())
追踪按钮事件,按钮被按下,并告知函数哪个按钮被按下了
from PyQt5.QtWidgets import QMainWindow, QPushButton , QWidget , QMessageBox, QApplication, QHBoxLayout
import sys
from functools import partial
class WinForm(QMainWindow):
def __init__(self, parent=None):
super(WinForm, self).__init__(parent)
self.setWindowTitle("信号和槽传递额外参数例子")
button1 = QPushButton('Button 1')
button2 = QPushButton('Button 2')
button1.clicked.connect(partial(self.onButtonClick, 1))
button2.clicked.connect(partial(self.onButtonClick, 2))
layout = QHBoxLayout()
layout.addWidget(button1)
layout.addWidget(button2)
main_frame = QWidget()
main_frame.setLayout(layout)
self.setCentralWidget(main_frame)
def onButtonClick(self, n):
print('Button {0} 被按下了'.format(n))
QMessageBox.information(self, "信息提示框", 'Button {0} clicked'.format(n))
if __name__ == "__main__":
app = QApplication(sys.argv)
form = WinForm()
form.show()
sys.exit(app.exec_())
自定义按钮形状
import sys
from PyQt5.Qt import *
# 1. 创建一个应用程序对象
app = QApplication(sys.argv)
# 2.控件的操作
# 2.1创建控件
window = QWidget()
# 2.2设置控件
window.setWindowTitle("QAbstractButton")
window.resize(500, 500)
window.move(400, 250)
class Btn(QAbstractButton):
"""自定义的按钮控件,体验从按钮抽象基类继承"""
def paintEvent(self, evt) -> None:
painter = QPainter(self) # 创建一个画家;告诉画在什么地方
pen = QPen(QColor(20, 154, 151), 5) # 创建并设置一个笔
painter.setPen(pen) # 把笔给画家
painter.drawText(30, 30, self.text()) # 把按钮文字画在按钮上
painter.drawEllipse(0, 0, 100, 120) # 画个椭圆
btn = Btn(window)
btn.setText("ABC")
btn.resize(110, 150)
btn.clicked.connect(lambda: print("点击了这个按钮")) # 按钮被按下则执行里面的lambda函数(槽函数)
# 2.3展示控件
window.show()
# 3.应用程序的执行, 进入到消息循环
sys.exit(app.exec_())
为按钮添加图标,自动重复等
import sys
from PyQt5.Qt import *
app = QApplication(sys.argv)
window = QWidget()
window.setWindowTitle("按钮的功能测试")
window.resize(500, 500)
window.move(400, 250)
btn = QPushButton(window)
btn.setText("1")
def plus_one():
num = str(int(btn.text()) + 1)
btn.setText(num)
btn.pressed.connect(plus_one)
icon = QIcon("./resource/github.png") # 通过文件路径设置图标
size = QSize(40, 40) # 通过(int, int)设置图标大小
btn.setIcon(icon)
btn.setIconSize(size)
btn.setAutoRepeat(True) # 启动自动重复
btn.setAutoRepeatDelay(1000) # 按住多长时间(毫米)之后才开始自动重复
window.show()
sys.exit(app.exec_())
设置按钮点击的有效区域
import sys
from PyQt5 import QtGui
from PyQt5.Qt import *
app = QApplication(sys.argv)
window = QWidget()
window.setWindowTitle("QAbstractButton-点击有效区域")
window.resize(500, 500)
window.move(400, 250)
class Btn(QPushButton):
"""自定义的按钮类,重写hitButton方法来实现自定义按钮点击有效区域功能"""
def hitButton(self, point) -> bool:
circle_center_x = self.width() / 2
circle_center_y = self.height() / 2
hit_x = point.x()
hit_y = point.y()
distance = (
(hit_x - circle_center_x) ** 2 + (hit_y - circle_center_y) ** 2
) ** 0.5
# print(distance)
if distance < self.width() / 2:
return True
else:
return False
def paintEvent(self, a0: QtGui.QPaintEvent) -> None:
"""重写父类方法,实现在按钮上画一个圆"""
super().paintEvent(a0) # 实现父类方法的全部功能
painter = QPainter(self)
painter.setPen(QPen(QColor(0, 240, 240), 6))
painter.drawEllipse(self.rect()) # 在按钮上绘制一个圆
btn = Btn(window)
btn.setText("点击")
btn.resize(200, 200)
btn.move(100, 100)
btn.pressed.connect(lambda: print("按钮被点击了"))
window.show()
sys.exit(app.exec_())
右键菜单
import sys
from PyQt5.Qt import *
class Window(QWidget):
def contextMenuEvent(self, a0: QContextMenuEvent) -> None:
# print("展示菜单")
menu = QMenu(self)
new_action = QAction(QIcon("./resource/github.png"), "新建", menu)
new_action.triggered.connect(lambda: print("新建文件"))
menu.addAction(new_action)
menu.exec_(a0.globalPos()) # 把位置(全局)传递
# 1. 创建一个应用程序对象
app = QApplication(sys.argv)
# 2.控件的操作
# 2.1创建控件
window = Window()
# 2.2设置控件
window.setWindowTitle("右键菜单")
window.resize(500, 500)
window.move(400, 250)
def show_menu(point):
"""customContextMenuRequested 的槽函数"""
# print("自定义上下文菜单", point)
menu = QMenu(window)
exit_action = QAction(QIcon("./resource/github.png"), "关闭", menu)
exit_action.triggered.connect(lambda: exit())
menu.addAction(exit_action)
# 把相对控件的坐标 point 映射到全局位置
dest_point = window.mapToGlobal(point)
menu.exec_(dest_point) # 把位置(全局)传递
window.setContextMenuPolicy(Qt.CustomContextMenu)
window.customContextMenuRequested.connect(show_menu)
# 2.3展示控件
window.show()
# 3.应用程序的执行, 进入到消息循环
sys.exit(app.exec_())
带描述的按钮
import sys
from PyQt5.Qt import *
"""QCommandLinkButton 继承自 QPushButton"""
# 1. 创建一个应用程序对象
app = QApplication(sys.argv)
# 2.控件的操作
# 2.1创建控件
window = QWidget()
# 2.2设置控件
window.setWindowTitle("QCommandLinkButton的使用")
window.resize(500, 500)
window.move(400, 250)
btn = QCommandLinkButton("标题", "描述", window)
btn.setText("标题2")
btn.setDescription("这是描述2")
btn.setIcon(QIcon("./resource/github.png"))
# 2.3展示控件
window.show()
# 3.应用程序的执行, 进入到消息循环
sys.exit(app.exec_())
窗口的综合调整,创建一个无边框、半透明的窗口;自定义关闭、最大化、最小化三个按钮;实现能够点击用户区域拖动窗口
import sys
from PyQt5 import QtGui
from PyQt5.Qt import *
class Window(QWidget):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setWindowFlags(Qt.FramelessWindowHint) # 设置了无边框的 Flag
self.setWindowOpacity(0.85) # 设置不透明度
self.setWindowTitle("窗口综合案例")
self.setWindowIcon(QIcon("./resource/github.png"))
self.resize(500, 500)
self.move(400, 240)
self.top_margin = 1 # 三个按钮距离顶部的距离
self.btn_w = 32 # 按钮宽度
self.btn_h = 32 # 按钮高度
self.setup_ui()
def setup_ui(self):
close_btn = QPushButton(self)
self.close_btn = close_btn # 通过把局部变量存储为对象属性来实现跨方法使用
close_btn.setIcon(QIcon("./resource/github.png"))
close_btn.resize(self.btn_w, self.btn_h)
max_btn = QPushButton(self)
self.max_btn = max_btn # 通过把局部变量存储为对象属性来实现跨方法使用
max_btn.setIcon(QIcon("./resource/github.png"))
max_btn.resize(self.btn_w, self.btn_h)
mini_btn = QPushButton(self)
self.mini_btn = mini_btn # 通过把局部变量存储为对象属性来实现跨方法使用
mini_btn.setIcon(QIcon("./resource/github.png"))
mini_btn.resize(self.btn_w, self.btn_h)
# 监听按钮,连接信号与槽
close_btn.pressed.connect(lambda: self.close())
mini_btn.pressed.connect(lambda: self.showMinimized())
def max_normal():
"""最大化/恢复 按钮的槽函数"""
if self.isMaximized():
max_btn.setIcon(QIcon("./resource/github.png"))
self.label.setText("Hello World")
self.label.setStyleSheet("font-size: 30px;")
self.label.adjustSize()
self.showNormal()
else:
self.label.setText("Life is short, use Python.")
self.label.setStyleSheet("font-size: 40px;")
self.label.adjustSize()
self.showMaximized()
max_btn.setIcon(QIcon("./resource/github.png"))
max_btn.pressed.connect(max_normal)
label = QLabel("Hello World", self)
self.label = label
label.setStyleSheet("font-size: 30px;")
label.adjustSize()
lab_x = int((self.width() - label.width()) / 2)
lab_y = int((self.height() - label.height()) / 2)
label.move(lab_x, lab_y)
def resizeEvent(self, a0: QtGui.QResizeEvent) -> None:
"""当窗口大小改变时,重新移动三个按钮的位置"""
self.close_btn.move(self.width() - self.btn_w, self.top_margin)
self.max_btn.move(self.width() - self.btn_w * 2, self.top_margin)
self.mini_btn.move(self.width() - self.btn_w * 3, self.top_margin)
self.label.move(
int((self.width() - self.label.width()) / 2),
int((self.height() - self.label.height()) / 2),
)
def mousePressEvent(self, evt):
# print("鼠标按下")
if evt.button() == Qt.LeftButton: # 仅在鼠标左键按下时可以拖动
self.move_flag = True # 设置一个标记,确保只有在执行 mousePressEvent 之后才会执行 mouseMoveEvent
# 确定两个点(鼠标第一次按下的点,窗口当前所在的原始点)
self.mouse_x = evt.globalX()
self.mouse_y = evt.globalY()
# print(self.mouse_x, self.mouse_y)
self.origen_x = self.x()
self.origen_y = self.y()
def mouseMoveEvent(self, evt) -> None:
if self.move_flag:
# print(evt.globalX(), evt.globalY())
# 计算的是移动向量
move_x = evt.globalX() - self.mouse_x
move_y = evt.globalY() - self.mouse_y
dest_x = self.origen_x + move_x
dest_y = self.origen_y + move_y
self.move(dest_x, dest_y)
def mouseReleaseEvent(self, a0: QtGui.QMouseEvent) -> None:
self.move_flag = False # 鼠标释放后重置标记,避免无法释放拖动
app = QApplication(sys.argv)
# window = QWidget(flags=Qt.FramelessWindowHint) # (之前面向过程写法保留的一行)设置了无边框的 Flag
window = Window()
window.show()
sys.exit(app.exec_())