Pyside2笔记二

# -*- coding: utf-8 -*-
# 一个界面至少应该有标题,大小,菜单栏,工具栏,状态栏甚至应该具有某些布局等等,
# 并且要考虑到用户的一些使用习惯等等,例如获取焦点,自动切换,以用户为中心的人机交互设计

import sys
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import QApplication, QWidget, QLabel

app = QApplication(sys.argv)

# 使用QWidget创建一个Widget对象
widget = QWidget()
# 重新设置Widget的大小,宽度250,高度150
widget.resize(250,150)
# 设置窗口标题 Hello World
widget.setWindowTitle("Hello World")
# 在widget上添加一个label,注意要将widget作为一个参数传递给QLabel
label = QLabel("<font color=red size=30>Hello world </font>",widget)
# 将label移动到距离widget顶端距离50,左边距离50的位置
label.move(50,50)
widget.show()

sys.exit(app.exec_())

方便管理 进行封装

# !/usr/bin/python
# coding:utf-8

import sys
from PySide2.QtWidgets import QWidget, QLabel, QApplication


class Example(QWidget):
    """这里创建了一个Example类,Example类继承QWidget。
    因此,在构造函数中,需要调用超类的构造函数。"""
    def __init__(self):
        super(Example, self).__init__()
        self.initUI()

    def initUI(self):
        label = QLabel("<font color=red size=30>Hello World</font>", self)
        label.move(50, 50)
        self.setGeometry(300, 300, 250, 150)
        # setGeometry的功能主要有两个:定位Widget在桌面上的位置和设置窗口的大小,
        # 前两个参数设置距离屏幕left和top的距离,后两个参数设置窗口的高和宽
        self.setWindowTitle("Hello World")
        self.show()


def main():
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()

最后两句一般写成: sys.exit(app.exec_())

这里,之所以写成app.exec_() 而不是app.exec() 是因为exec是python中的关键字,所以Qt使用exec_避开。

另外,在PySide中可以使用html标签使内容更加丰富例如:
label = QLabel("<font color=red size=30>Hello World</font>", self)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容