PYQT5布局,一些基础demo(小白必看)

PyQT



w = QWidget()

# 创建一个label 纯文本, 创建时指定父对象 w
# label = QLabel('账号:')
# label.setParent(w)
label = QLabel('账号:', w)


# 设置大小 (x,y,w,h)
label.setGeometry(20,20,30,30)


# 设置窗口在屏幕中央显示
center_pointer = QDesktopWidget().availableGeometry().center()
x = center_pointer.x()
y = center_pointer.y()

w.move(x,y)
登录布局

import sys

from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QVBoxLayout, QFormLayout, QLineEdit, QPushButton, QApplication, QWidget


class MyWindow(QWidget):

    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        # 设定当前Widget的宽高(可以拉伸大小)
        # self.resize(300, 200)
        # 禁止改变宽高(不可以拉伸)
        self.setFixedSize(300, 150)

        # 外层容器
        container = QVBoxLayout()

        # 表单容器
        form_layout = QFormLayout()

        # 创建1个输入框
        edit = QLineEdit()
        edit.setPlaceholderText("请输入账号")
        form_layout.addRow("账号:", edit)

        # 创建另外1个输入框
        edit2 = QLineEdit()
        edit2.setPlaceholderText("请输入密码")
        form_layout.addRow("密码:", edit2)

        # 将from_layout添加到垂直布局器中
        container.addLayout(form_layout)

        # 按钮
        login_btn = QPushButton("登录")
        login_btn.setFixedSize(100, 30)

        # 把按钮添加到容器中,并且指定它的对齐方式
        container.addWidget(login_btn, alignment=Qt.AlignRight)

        # 设置当前Widget的布局器,从而显示这个布局器中的子控件
        self.setLayout(container)


if __name__ == '__main__':
    app = QApplication(sys.argv)

    w = MyWindow()
    w.show()

    app.exec()

抽屉布局

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QStackedLayout, QLabel


class Window1(QWidget):
    def __init__(self):
        super().__init__()
        QLabel("我是抽屉1要显示的内容", self)
        self.setStyleSheet("background-color:green;")


class Window2(QWidget):
    def __init__(self):
        super().__init__()
        QLabel("我是抽屉2要显示的内容", self)
        self.setStyleSheet("background-color:red;")


class MyWindow(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.create_stacked_layout()
        self.init_ui()

    def create_stacked_layout(self):
        # 创建堆叠(抽屉)布局
        self.stacked_layout = QStackedLayout()
        # 创建单独的Widget
        win1 = Window1()
        win2 = Window2()
        # 将创建的2个Widget添加到抽屉布局器中
        self.stacked_layout.addWidget(win1)
        self.stacked_layout.addWidget(win2)

    def init_ui(self):
        # 设置Widget大小以及固定宽高
        self.setFixedSize(300, 270)

        # 1. 创建整体的布局器
        container = QVBoxLayout()

        # 2. 创建1个要显示具体内容的子Widget
        widget = QWidget()
        widget.setLayout(self.stacked_layout)
        widget.setStyleSheet("background-color:grey;")

        # 3. 创建2个按钮,用来点击进行切换抽屉布局器中的Widget
        btn_press1 = QPushButton("抽屉1")
        btn_press2 = QPushButton("抽屉2")
        # 给按钮添加事件(即点击后要调用的函数)
        btn_press1.clicked.connect(self.btn_press1_clicked)
        btn_press2.clicked.connect(self.btn_press2_clicked)

        # 4. 将需要显示的空间添加到布局器中
        container.addWidget(widget)
        container.addWidget(btn_press1)
        container.addWidget(btn_press2)

        # 5. 设置当前要显示的Widget,从而能够显示这个布局器中的控件
        self.setLayout(container)

    def btn_press1_clicked(self):
        # 设置抽屉布局器的当前索引值,即可切换显示哪个Widget
        self.stacked_layout.setCurrentIndex(0)

    def btn_press2_clicked(self):
        # 设置抽屉布局器的当前索引值,即可切换显示哪个Widget
        self.stacked_layout.setCurrentIndex(1)


if __name__ == "__main__":
    app = QApplication(sys.argv)

    win = MyWindow()
    win.show()

    app.exec()
下拉选择框QCombox和数字调节框QSpinBox
下拉列表  


import sys
from PyQt5.QtWidgets import QApplication, QWidget, QComboBox, QFontComboBox, QLineEdit, QMessageBox, QVBoxLayout
 
 
class Demo(QWidget):
    choice = 'a'
    choice_list = ['b', 'c', 'd', 'e']
 
    def __init__(self):
        super(Demo, self).__init__()
 
        self.combobox_1 = QComboBox(self)                   # 1
        self.combobox_2 = QFontComboBox(self)               # 2

 		# 1.实例化一个QComboBox和QFontComboBox,前者是普通的下拉框,框里是没有内容的,需要添加。而QFontComboBox
 		# 2.  是字体下拉框,继承于QComboBox,该字体下拉框里会默认有许多字体供选择;
        self.lineedit = QLineEdit(self)                     # 3
 
        self.v_layout = QVBoxLayout()
 		
 		# 3.这里实例化一个单行文本输入框,用于测试从字体下拉框中选择一项时,输入框中字体发生的变化;
        self.layout_init()
        self.combobox_init()
 
    def layout_init(self):
        self.v_layout.addWidget(self.combobox_1)
        self.v_layout.addWidget(self.combobox_2)
        self.v_layout.addWidget(self.lineedit)
 
        self.setLayout(self.v_layout)
 
    def combobox_init(self):
        self.combobox_1.addItem(self.choice)              # 4
        self.combobox_1.addItems(self.choice_list)        # 5

        #  4-5. addItem()方法是添加一个选项,而addItems()接收一个可循环参数,
        #  这里传入了列表self.choice_list;

        self.combobox_1.currentIndexChanged.connect(lambda: self.on_combobox_func(self.combobox_1))   # 6
        # self.combobox_1.currentTextChanged.connect(lambda: self.on_combobox_func(self.combobox_1))  # 7
 
        self.combobox_2.currentFontChanged.connect(lambda: self.on_combobox_func(self.combobox_2))
        # self.combobox_2.currentFontChanged.connect(lambda: self.on_combobox_func(self.combobox_2))
 		
 		# 6-7.当下拉框当前选项发生变化变化的话,则会触发序号变化currentIndexChanged信号和文本变化currentTextC
 		# hanged信号,我们在这里进行了信号与槽的连接,注意槽函数是带参数的,所以我们用lambda表达式进行处理;

    def on_combobox_func(self, combobox):                                                             # 8
        if combobox == self.combobox_1:
            QMessageBox.information(self, 'ComboBox 1', '{}: {}'.format(combobox.currentIndex(), combobox.currentText()))
        else:
            self.lineedit.setFont(combobox.currentFont())
 	
 	# 8. 在自定义的槽函数中,我们通过判断combobox的种类,若是self.combobox_1的话,则出现信息框,并且显示当前文本
 	# 和及文本序号,currentIndex()方法获取当前文本序号,currentText()方法获取当前文本。若是self.combobox_2的话
 	# ,则通过setFont()方法将输入框的字体设为当前选中的字体,currentFont()获取字体下拉框的当前字体。
 
if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = Demo()
    demo.show()
    sys.exit(app.exec_())


个性化配置

Qt只设置Qwidget 背景色

pyqt5 给按钮设置css样式和界面背景设置

import sys
from PyQt5.QtWidgets import QWidget, QPushButton, QApplication
from PyQt5.QtGui import QPalette, QBrush, QPixmap
 
 
 
class Example(QWidget):
    
    def __init__(self):
        super().__init__()
        
        self.initUI() #界面绘制交给InitUi方法
        
        
    def initUI(self):
        
        self.button = QPushButton('按钮', self)
        
        self.button.setStyleSheet("QPushButton{color:black}"
                                  "QPushButton:hover{color:red}"
                                  "QPushButton{background-color:rgb(78,255,255)}"
                                  "QPushButton{border:2px}"
                                  "QPushButton{border-radius:10px}"
                                  "QPushButton{padding:2px 4px}")
        
        self.button.setMinimumHeight(30)
        self.button.move(100, 100)
        
        #设置窗口的位置和大小
        self.setGeometry(300, 300, 500, 500)  
        #设置窗口的标题
        self.setWindowTitle('Example')
        
        #设置背景图片
        palette1 = QPalette()
        palette1.setBrush(self.backgroundRole(), QBrush(QPixmap('background.jpg')))
        self.setPalette(palette1)
        
        
        #显示窗口
        self.show()
        
        
if __name__ == '__main__':
    #创建应用程序和对象
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

圆盘+ 数字调节框



import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import (QApplication, QWidget, QDial,
                             QLabel, QHBoxLayout, QSpinBox)


class DemoDial (QWidget):
	def __init__(self, parent=None):
		super (DemoDial, self).__init__ (parent)

		# 设置窗口标题
		self.setWindowTitle ('实战PyQt5: QDial Demo!')
		# 设置窗口大小
		self.resize (400, 300)

		self.initUi ()

	def initUi(self):
		self.dial = QDial (self)
		# 表盘大小
		self.dial.setFixedSize (100, 100)
		# 刻度的范围
		self.dial.setRange (0, 200)
		#  刻度之间 刻度
		self.dial.setNotchesVisible (True)
		#  表盘刻度发生变化, 调用槽函数
		self.dial.valueChanged.connect (self.onDialValueChanged)

		self.spinbox = QSpinBox (self)
		self.spinbox.setRange (0, 200)  # 1
		# 设置 ,步长, 减一下
		self.spinbox.setSingleStep (1)
		# 设置默认显示 0
		self.spinbox.setValue (0)
		self.spinbox.valueChanged.connect (self.value_change_func)



		# self.labValue = QLabel ('0', self)
		# self.labValue.setFont (QFont ('Arial Black', 24))

		hLayout = QHBoxLayout (self)
		hLayout.addWidget (self.dial)
		# hLayout.addWidget (self.labValue)
		hLayout.addWidget (self.spinbox)

		self.setLayout (hLayout)

	def onDialValueChanged(self):
		self.spinbox.setValue (str (self.dial.value ()))

	def value_change_func(self):
		self.dial.setValue(self.spinbox.value())


if __name__ == '__main__':
	app = QApplication (sys.argv)
	window = DemoDial ()
	window.show ()

	sys.exit (app.exec ())


  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
PyQt5提供了多种布局管理器,以便更轻松地创建GUI应用程序。以下是几个常用的布局管理器: 1. QVBoxLayout(垂直布局) 将控件在垂直方向上排列。 ```python from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton app = QApplication([]) window = QWidget() layout = QVBoxLayout() layout.addWidget(QPushButton('Button 1')) layout.addWidget(QPushButton('Button 2')) layout.addWidget(QPushButton('Button 3')) window.setLayout(layout) window.show() app.exec_() ``` 2. QHBoxLayout(水平布局) 将控件在水平方向上排列。 ```python from PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout, QPushButton app = QApplication([]) window = QWidget() layout = QHBoxLayout() layout.addWidget(QPushButton('Button 1')) layout.addWidget(QPushButton('Button 2')) layout.addWidget(QPushButton('Button 3')) window.setLayout(layout) window.show() app.exec_() ``` 3. QGridLayout(网格布局) 将控件排列在网格中。 ```python from PyQt5.QtWidgets import QApplication, QWidget, QGridLayout, QPushButton app = QApplication([]) window = QWidget() layout = QGridLayout() layout.addWidget(QPushButton('Button 1'), 0, 0) layout.addWidget(QPushButton('Button 2'), 0, 1) layout.addWidget(QPushButton('Button 3'), 1, 0) layout.addWidget(QPushButton('Button 4'), 1, 1) window.setLayout(layout) window.show() app.exec_() ``` 4. QFormLayout(表单布局) 将标签和输入控件排列在一起,以形成表单。 ```python from PyQt5.QtWidgets import QApplication, QWidget, QFormLayout, QLineEdit, QLabel app = QApplication([]) window = QWidget() layout = QFormLayout() layout.addRow(QLabel('Name:'), QLineEdit()) layout.addRow(QLabel('Age:'), QLineEdit()) layout.addRow(QLabel('Email:'), QLineEdit()) window.setLayout(layout) window.show() app.exec_() ``` 以上是一些常用的布局管理器,你也可以自己实现并自定义布局管理器。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值