QLabel
用于顯示文本資訊,
常用方法:
setAlignment():設定文本的對齊方式 (align對齊,對準,使結盟,匹配)
setIndent():設定文本縮進
text():獲取文本內容
setBuddy():設定伙伴關系 (buddy伙伴)
setText():設定文本內容
selectedText():回傳所選擇的字符
setWordWrap():設定是否允許換行
QLabel常用的信號(事件) :
1.當滑鼠滑過QLabel控制元件時觸發: linkHovered
2.當滑鼠單擊QLabel控制元件時觸發: linkActivated
代碼:
import sys
from PyQt5.QtWidgets import QApplication,QLabel,QWidget,QVBoxLayout #垂直布局
from PyQt5.QtGui import QPalette # 調色版
from PyQt5.QtGui import QPixmap #展示圖片
from PyQt5.QtCore import Qt #有一些常量在這里面,eg:blue
class QLabelDdemo(QWidget):
def __init__(self):
super(QLabelDdemo, self).__init__()
self.initUI()
def initUI(self):
label1=QLabel(self)
label2 = QLabel(self)
label3 = QLabel(self)
label4 = QLabel(self)
label1.setText('<font color=yellow>這是一個文本標簽</font>')
label1.setAutoFillBackground(True) #自動填充背景
palette=QPalette()
#設定背景色
palette.setColor(QPalette.Window,Qt.blue)
#對label1設定調色版
label1.setPalette(palette)
#跳轉到一個網頁或者觸發一個點擊事件
label2.setText("<a href='#'>歡迎使用Python GUI程式</a>")
#文本居中
label3.setAlignment(Qt.AlignCenter)
#提示資訊
label3.setToolTip('這是一個圖片標簽')
label3.setPixmap(QPixmap('../pure_code/icon/first.png'))
#如果設為True,用瀏覽器打開網頁,如果設為False,呼叫槽函式
label4.setOpenExternalLinks(True)
label4.setText("<a href='www.baidu.com'>你好鴨,小仙女</a>")
# 右對齊
label4.setAlignment(Qt.AlignRight)
label4.setToolTip('這是一個超級鏈接')
vbox=QVBoxLayout()
vbox.addWidget(label1)
vbox.addWidget(label2)
vbox.addWidget(label3)
vbox.addWidget(label4)
# 系結信號和槽
#滑過事件
label2.linkHovered.connect(self.linkHovered)
#單擊事件
label4.linkActivated.connect(self.linkClicked)
self.setLayout(vbox)
self.setWindowTitle('QLabel控制元件演示')
self.resize(400,300)
return
def linkHovered(self):
print('當滑鼠滑過label2標簽時,觸發事件')
def linkClicked(self):
print('當滑鼠單擊label4標簽時,觸發事件')
if __name__=='__main__':
app=QApplication(sys.argv)
main=QLabelDdemo()
main.show()
sys.exit(app.exec_())
報錯
palette.setColor(QPalette.window,Qt.blue)
TypeError: arguments did not match any overloaded call:
setColor(self, QPalette.ColorGroup, QPalette.ColorRole, Union[QColor, Qt.GlobalColor, QGradient]): argument 1 has unexpected type 'builtin_function_or_method'
setColor(self, QPalette.ColorRole, Union[QColor, Qt.GlobalColor, QGradient]): argument 1 has unexpected type 'builtin_function_or_method'
原因:
palette.setColor(QPalette.window,Qt.blue)里的Window開頭得大寫!
運行結果:

當滑鼠從第二層(因為是垂直布局,我就按層說了)那個鏈接滑過時,就會觸發相應的事件(槽函式),輸出了相應的文字
當點擊第四層的鏈接時,會觸發自己寫的槽函式,卻不會跳轉到相應的超鏈接界面,要如下額外設定一下,
#如果設為True,用瀏覽器打開網頁,如果設為False,呼叫槽函式
label4.setOpenExternalLinks(True)
設定了之后,就只能跳轉(此跳轉是自動打開你的瀏覽器跳轉到相應界面)而不會再觸發槽函式!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/247656.html
標籤:python
上一篇:Linux內核開發人員考慮剔除對更多老舊平臺的處理器支持
下一篇:Pygame(十二)打磚塊
