python pyqt5怎么让按钮有触感
时间: 2024-12-04 13:29:07 浏览: 43
在PyQt5中,为了让按钮添加点击或触摸的触感效果,通常我们会使用`QPushButton`控件,并结合CSS样式或自定义槽函数来实现。以下是一个简单的例子:
```python
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt
class TouchButton(QWidget):
def __init__(self):
super().__init__()
self.button = QPushButton("点击我", self)
self.button.setCursor(Qt.OpenHandCursor) # 设置鼠标悬停图标
self.button.setStyleSheet("border-radius: 8px; padding: 10px 20px; background-color: #f4f4f4; border: 2px solid #ddd; transition: background-color 0.2s ease-in-out;")
# 添加鼠标悬停和按下效果
self.button.setCursor(Qt.ClosedHandCursor) # 鼠标按下时的图标
self.button.clicked.connect(self.on_button_clicked)
def on_button_clicked(self):
self.button.setStyleSheet("background-color: #d9d9d9; border-color: #8c8c8c;") # 点击后的颜色变化
QTimer.singleShot(200, lambda: self.button.setStyleSheet('')) # 延迟200毫秒恢复原色
if __name__ == "__main__":
app = QApplication([])
window = TouchButton()
window.show()
app.exec_()
```
在这个示例中,我们创建了一个带有圆角、边框和淡灰色背景的按钮。当鼠标悬停时,改变鼠标图标;点击时,按钮背景颜色变暗,并在一段时间后恢复原状,模拟了触感效果。
阅读全文
相关推荐















