PyQt6 文本框添加自定义图标教程 - 使用 QStyle 和 QLineEdit
要在 PyQt6 中为文本框添加自定义图标,你可以使用 QLineEdit 类,并通过 QStyle 类的 standardIcon() 方法获取标准图标,然后使用 QLineEdit 的 setStyleSheet() 方法将图标添加到文本框中。
下面是一个示例代码:
from PyQt6.QtWidgets import QApplication, QWidget, QLineEdit
from PyQt6.QtGui import QStyle
class MyWidget(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(100, 100, 300, 200)
lineEdit = QLineEdit(self)
lineEdit.setGeometry(50, 50, 200, 30)
# 获取标准图标
icon = self.style().standardIcon(QStyle.StandardPixmap.SP_FileIcon)
# 设置图标样式
lineEdit.setStyleSheet(f'QLineEdit {{ background-image: url({icon}); background-repeat: no-repeat; background-position: left center; padding-left: 20px; }}')
app = QApplication([])
widget = MyWidget()
widget.show()
app.exec()
在上面的示例中,我们创建了一个自定义的 QWidget 类,并在其 initUI() 方法中创建了一个 QLineEdit 对象。然后,我们使用 QStyle 类的 standardIcon() 方法获取了一个标准图标(这里是文件图标),并使用 setStyleSheet() 方法将图标添加到文本框的背景中。
请注意,这里使用了 QLineEdit 的 background-image 属性来设置背景图像,并使用 background-position 和 padding-left 属性来调整图标的位置和文本框的填充。你可以根据需要调整这些属性的值。
希望能帮到你!
原文地址: https://www.cveoy.top/t/topic/p40n 著作权归作者所有。请勿转载和采集!