QLabel 显示字符串时,显示多种颜色
时间: 2024-05-10 21:17:21 浏览: 77
可以使用富文本格式来设置 QLabel 的文本,从而实现多种颜色的显示。具体方法是:使用 HTML 标记将文本分段,并在每个段落中使用 `<font>` 标记设置不同的颜色和其他属性。然后将整个文本作为富文本字符串传递给 QLabel 的 `setText()` 方法。
以下是一个示例代码,将 QLabel 显示为红色和蓝色文本:
```python
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel
app = QApplication([])
window = QWidget()
label = QLabel()
text = "<font color='red'>Hello</font> <font color='blue'>world</font>!"
label.setText(text)
layout = QVBoxLayout()
layout.addWidget(label)
window.setLayout(layout)
window.show()
app.exec_()
```
在这个例子中,我们首先创建了一个 QLabel,并设置了一个富文本字符串。这个字符串包含两个段落,分别使用 `<font>` 标记设置了不同的颜色。然后将这个字符串设置为 QLabel 的文本,并将 QLabel 放置在一个 QVBoxLayout 布局中,最后显示整个窗口。
可以根据需要使用不同的 HTML 标记来设置文本的属性,例如 `<b>` 标记可以设置加粗,`<i>` 标记可以设置斜体等等。
阅读全文
相关推荐


















