📅  最后修改于: 2023-12-03 15:18:49.594000             🧑  作者: Mango
在 PyQt5 中,使用 QSpinBox 来创建一个数字选择框。为了增强用户体验,在按下数字选择框时可以添加背景颜色。下面是实现的步骤:
from PyQt5.QtWidgets import QApplication, QSpinBox
from PyQt5.QtGui import QColor
spinbox = QSpinBox()
def mousePressEvent(self, event):
self.setStyleSheet("background-color: #D9D9D9;")
def mouseReleaseEvent(self, event):
self.setStyleSheet("")
if __name__ == '__main__':
app = QApplication(sys.argv)
win = MyWindow()
win.show()
sys.exit(app.exec_())
完整代码示例:
import sys
from PyQt5.QtWidgets import QApplication, QSpinBox
from PyQt5.QtGui import QColor
class MySpinBox(QSpinBox):
def mousePressEvent(self, event):
self.setStyleSheet("background-color: #D9D9D9;")
def mouseReleaseEvent(self, event):
self.setStyleSheet("")
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
spinbox = MySpinBox()
self.setCentralWidget(spinbox)
if __name__ == '__main__':
app = QApplication(sys.argv)
win = MyWindow()
win.show()
sys.exit(app.exec_())
运行效果: