python3 pyqt6 文本框 自定义图标
要在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/im0d 著作权归作者所有。请勿转载和采集!