QLineEdit
是 PyQt 中常用的一个用于输入单行文本的控件,
setStyleSheet
方法可以设置该控件的样式表。
使用
setStyleSheet
方法可以通过 CSS 样式表的方式来改变
QLineEdit
的样式,具体步骤如下:
创建一个
QLineEdit
对象
from PyQt5.QtWidgets import QLineEdit
line_edit = QLineEdit()
使用 setStyleSheet
方法设置样式表
line_edit.setStyleSheet("background-color: yellow; color: blue; border: 2px solid green;")
上面的样式表设置了 QLineEdit
的背景色为黄色,字体颜色为蓝色,边框为绿色实线,边框宽度为 2 像素。
完整的代码示例:
from PyQt5.QtWidgets import QApplication, QWidget, QLineEdit, QVBoxLayout
app = QApplication([])
window = QWidget()
line_edit = QLineEdit()
line_edit.setStyleSheet("background-color: yellow; color: blue; border: 2px solid green;")
layout = QVBoxLayout()
layout.addWidget(line_edit)
window.setLayout(layout)
window.show()
app.exec_()
运行代码后,会显示一个带有黄色背景、蓝色字体、绿色实线边框的 QLineEdit
控件。
需要注意的是,在设置样式表时要遵循 CSS 的语法规则,例如属性和值之间要用冒号分隔,多个属性之间要用分号分隔等。