亲宝软件园·资讯

展开

Python PyQt5学习之样式设置详解

SongYuLong的博客 人气:0

为标签添加背景图片

import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = QMainWindow()
    label = QLabel()
    label.setToolTip("这是一个文本标签")
    label.setStyleSheet("QLabel{border-image:url(./pyqt5/images/python.jpg)};")
    label.setFixedWidth(320)
    label.setFixedHeight(200)

    win.setCentralWidget(label)
    win.show()
    sys.exit(app.exec_())

为按钮添加背景图片

import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = QWidget()
    layout = QVBoxLayout()
    btn1 = QPushButton("按钮1")
    btn1.setMaximumSize(48, 48)
    btn1.setMinimumSize(48, 48)
    style = '''
        QPushButton {
            border-radius: 30px;
            background-image: url('./pyqt5/images/left.png');
        }
    '''
    btn1.setStyleSheet(style)
    layout.addWidget(btn1)
    win.setLayout(layout)
    win.show()
    sys.exit(app.exec_())

import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *


if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = QWidget()
    btn1 = QPushButton("按钮1")
    btn1.setFixedSize(50, 50)
    btn1.setObjectName("btn1")
    style = '''
        #btn1{
            border-radius: 30px;
            background-image: url('./pyqt5/images/left.png')
        }

        #btn1:hover{
            border-radius: 30px;
            background-image: url('./pyqt5/images/leftHover.png')
        }

        #btn1:Pressed{
            border-radius: 30px;
            background-image: url('./pyqt5/images/leftPressed.png')
        }
    '''
    btn1.setStyleSheet(style)
    layout = QVBoxLayout()
    layout.addWidget(btn1)
    win.setLayout(layout)
    win.show()
    sys.exit(app.exec_())

缩放图片

import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = QWidget()
    pic = r"./pyqt5/images/Cloudy_72px.png"
    img = QImage(pic)
    label1 = QLabel()
    label1.setFixedWidth(120)
    label1.setFixedHeight(120)
    result = img.scaled(label1.width(), label1.height(), Qt.IgnoreAspectRatio, Qt.SmoothTransformation)

    label1.setPixmap(QPixmap.fromImage(result))
    label2 = QLabel()
    label2.setPixmap(QPixmap.fromImage(img))
    layout = QVBoxLayout()
    layout.addWidget(label2)
    layout.addWidget(label1)
    win.setLayout(layout)
    win.show()
    sys.exit(app.exec_())

设置窗口透明

import sys

from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = QMainWindow()
    win.setWindowTitle("设置窗口透明")
    win.setWindowOpacity(0.5) # 设置窗口透明  透明度取值范围:0.0(全透明)~1.0(不透明),默认值1.0
    win.show()
    sys.exit(app.exec_())

加载全部内容

相关教程
猜你喜欢
用户评论