QPushButton设置Icon怎么预留白边
时间: 2023-10-09 16:12:27 浏览: 42
如果您想要在 `QPushButton` 中设置一个 `Icon` 并且希望它周围有一些留白,可以使用 `QIcon` 的 `pixmap()` 方法来创建一个带有留白的 `QPixmap`,然后将其设置为 `QPushButton` 的 `Icon`。
以下是一个示例代码:
```python
from PyQt5.QtGui import QIcon, QPixmap
from PyQt5.QtWidgets import QApplication, QPushButton
app = QApplication([])
# 创建一个 64x64 的 QPixmap,并在左、上、右、下各留出 10 个像素的留白
pixmap = QPixmap(64, 64)
pixmap.fill()
pixmap = pixmap.scaled(44, 44, aspectRatioMode=True, transformMode=QtCore.Qt.SmoothTransformation)
pixmap.fill(QtGui.QColor(0,0,0))
pixmap.setMask(pixmap.createHeuristicMask())
# 将留白后的 QPixmap 转换为 QIcon,并设置为 QPushButton 的图标
button = QPushButton()
button.setIcon(QIcon(pixmap))
button.show()
app.exec_()
```
在这个示例中,我们首先创建一个大小为 64x64 的 `QPixmap`,然后使用 `fill()` 方法将其填充为白色。接下来,我们使用 `scaled()` 方法将其缩小为 44x44 大小,并在左、上、右、下各留出 10 个像素的留白。最后,我们使用 `setMask()` 方法将留白后的 `QPixmap` 转换为 `QIcon` 并设置为 `QPushButton` 的图标。