编程环境:Fedora, QtCreator
见代码:
# This Python file uses the following encoding: utf-8
import sys
from PySide6.QtWidgets import QApplication, QMainWindow, QLabel, QVBoxLayout, QWidget
from PySide6.QtGui import QPalette #, QColor
from PySide6.QtCore import Qt
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("label控件")
self.resize(800, 400)
#self.status = self.statusBar()
layout = QVBoxLayout()
widget = QWidget(self)
widget.setLayout(layout)
widget.setGeometry(50, 50, 700, 300)
#self.setCentralWidget(widget)
self.widget = widget
label_normal = QLabel(self)
label_normal.setText("这是一个普通标签,居中。")
label_normal.setAlignment(Qt.AlignCenter)
label_normal.setFixedHeight(30)
layout.addWidget(label_normal)
label_color = QLabel(self)
label_color.setText("这是一个有红色背景白色字体的标签,左对齐。")
label_color.setAutoFillBackground(True)
palette = QPalette()
palette.setColor(QPalette.Window, Qt.red)
palette.setColor(QPalette.WindowText, Qt.white)
label_color.setPalette(palette)
label_color.setAlignment(Qt.AlignLeft)
label_color.setFixedHeight(30)
layout.addWidget(label_color)
label_html = QLabel(self)
label_html.setText("<a href='#'>这是一个HTML标签</a><font color='red'><i>Hello</i> <b>World</b> </font>")
label_html.setAlignment(Qt.AlignRight)
label_html.setFixedHeight(30)
layout.addWidget(label_html)
label_hover = QLabel(self)
label_hover.setText("<a href='#'>指针滑过该标签时触发事件</a>")
label_hover.linkHovered.connect(self.link_hovered)
label_hover.setFixedHeight(30)
label_hover.setAlignment(Qt.AlignLeft)
layout.addWidget(label_hover)
label_click = QLabel(self)
label_click.setText("<a href='http://www.baidu.com'>单击可以打开百度</a>")
label_click.setOpenExternalLinks(True)
label_click.setFixedHeight(30)
label_click.setAlignment(Qt.AlignLeft)
layout.addWidget(label_click)
def link_hovered(self):
print("指针滑过时触发事件")
if __name__ == "__main__":
app = QApplication([])
window = MainWindow()
window.show()
sys.exit(app.exec())
执行效果: