📅  最后修改于: 2023-12-03 15:33:54.776000             🧑  作者: Mango
在 PyQt5 中,我们可以使用 QComboBox 来创建一个下拉列表框。有时候,我们希望在鼠标悬停在下拉列表框的 lineedit 部分时添加一个边框,以便提醒用户。下面是如何实现该功能的步骤。
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QCursor
from PyQt5.QtWidgets import QApplication, QComboBox, QStyleOptionComboBox, QStylePainter, QStyleFactory
class CustomComboBox(QComboBox):
def __init__(self, *args, **kwargs):
super(CustomComboBox, self).__init__(*args, **kwargs)
self.hovered = False
self.initUI()
def initUI(self):
self.setFixedHeight(30)
self.setContentsMargins(5, 0, 5, 0)
def paintEvent(self, event):
opt = QStyleOptionComboBox()
self.initStyleOption(opt)
painter = QStylePainter(self)
painter.setPen(self.palette().color(self.foregroundRole()))
if self.hovered:
opt.state |= QStyle.State_MouseOver
if self.hasFocus():
opt.state |= QStyle.State_HasFocus
painter.drawComplexControl(QStyle.CC_ComboBox, opt)
textRect = self.style().subControlRect(QStyle.CC_ComboBox, opt, QStyle.SC_ComboBoxEditField, self)
painter.drawText(textRect, Qt.AlignLeft | Qt.AlignVCenter, self.currentText())
def leaveEvent(self, event):
self.hovered = False
self.update()
def enterEvent(self, event):
self.hovered = True
self.update()
def mousePressEvent(self, event):
self.hovered = False
self.update()
super(CustomComboBox, self).mousePressEvent(event)
def changeEvent(self, event):
if event.type() == event.FontChange:
self.updateGeometry()
super(CustomComboBox, self).changeEvent(event)
CustomComboBox
的类,继承自 QComboBox。hovered
,用于判断鼠标是否在 lineedit 部分悬停。initUI()
方法,用于初始化一些样式参数。其中,调用了 setFixedHeight 方法设置下拉列表框的高度,并调用了 setContentsMargins 方法设置 lineedit 边框的内边距。hovered
变量的值,并强制重绘。