📅  最后修改于: 2023-12-03 15:03:56.014000             🧑  作者: Mango
组合框(QComboBox)是PyQt5中常用的控件之一,可以让用户从预定义的列表中选择一个选项。本文将介绍如何制作一个圆形的组合框。
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class RoundComboBox(QComboBox):
def __init__(self, parent=None):
super().__init__(parent)
self.setStyleSheet("""
QComboBox {{
border: 1px solid gray;
border-radius: 30px;
color: black;
padding: 3px 18px 3px 3px;
background: white;
font-size: 14px;
selection-background-color: #F5A9A9;
height: 32px;
}}
QComboBox QAbstractItemView {{
border: 1px solid gray;
selection-background-color: #E6E6E6;
background: white;
}}
""") # 设置样式表
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing) # 抗锯齿
painter.setPen(Qt.NoPen)
painter.setBrush(QBrush(QColor("#E6E6E6"))) # 填充颜色
painter.drawEllipse(self.rect())
super().paintEvent(event)
def showPopup(self):
super().showPopup()
self.view().move(self.view().pos().x(), self.view().pos().y() + 32) # 下拉框向下平移
def mousePressEvent(self, event):
if event.pos().x() > self.width() - 35: # 判断是否点击到圆形区域
super().mousePressEvent(event)
if __name__ == '__main__':
app = QApplication([])
combo_box = RoundComboBox()
combo_box.addItems(["Item 1", "Item 2", "Item 3"])
combo_box.show()
app.exec()
通过以上实现,我们就可以得到一个圆形的组合框。