PyQT5 基本控件介绍一(QLable, QPushButton, QRadioButton)

447 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

简单介绍下PyQt5中常见的一些控件用法 QLable, QPushButton, QRadioButton

QLabel

初始化,构造函数

label = QLabel(text)
#text为需要设置的文本信息

设置文本信息

label.setText(text)

获取label文本信息

message = label.text()

设置文本的对其方式

label.setAlignment(alignment)
# 注解alignment有以下这四种形式(水平方向)
# Qt.AlignLeft
# Qt.AlignHCenter
# Qt.AlignRight
# Qt.ALignJsutify
# 注解alignment有以下这四种形式(垂直方向)
# Qt.AlignTop
# Qt.AlignVCenter
# Qt.AlignBottom
# Qt.AlignBaseline

自动换行设置,当文本内容比较多的时候

lable.setWordWrap(True)

设置margin,类似Android里面的的Margin

lable.setMargin(margin)

指定缩进

lable.setIndent(indent)

QPushButton

构造函数, label是显示在button的文本

pushbutton = QPushButton(label)

设置文本

pushbutton.setText(text)

设置Flat,不显示button

pushButton.setFlat(flat)

获取button的Flat是否设置了Flat

pushButton.isFlat()

按钮设置点击显示菜单

pushButton.setMenu(menu)
#这里也就是说明不是非要那种下拉的控件才能做这种效果(如下图),一般的button控件也能达到这样的效果
'''
1,创建一个QPushButton
	button = QPushButton("click me")
2, 创建一个QMenu
	menu = Qmneu()
3, 给menu添加子菜单并且绑定事件
	menu.addAction("hello", self.hello)
	这里的引号里面的hello表示的是子菜单的显示的名字,而后面的hello表示的如果点击了这个子菜单应该执行哪一个函数。

'''

按钮的点击事件,最基础的信号

pushButton.clicked.connect(button_clicked_function)

设置鼠标移动到上面有提示提示

button.setToolTip("点击退出程序")

QRadioButton

构造函数 radiobutton = QRadioButton(label)


设置文本 radiobutton.setText(label)


获取文本 radiobutton.text()


是否可以被点击 radiobutton.setChecked(checked)

--

获取点击的状态 radiobutton.isChecked()

设置图片 radioButton.setICon(icon)


代码如下:

from PyQt5.QtWidgets import *
import sys

class Window(QWidget):
	def __init__(self):
		QWidget.__init__(self)
		layout = QGridLayout()
		self.setLayout(layout)

		radiobutton = QRadioButton("Brazil")
		radiobutton.setChecked(True)
		# 有些人可能对着country属性不理解,这里是小编自己定义的一个属性
		radiobutton.country = "Brazil"
		radiobutton.toggled.connect(self.on_roadio_button_toggled)
		layout.addWidget(radiobutton,0 ,0)
		
		radiobutton = QRadioButton("Argentina")
		radiobutton.country = "Argentina"
		radiobutton.toggled.connect(self.on_radio_button_toggled)
		layout.addWidget(radiobutton, 0, 1)
		
		radiobutton = QRadioButton("Ecuador")
		radiobutton.country = "Ecuador"
		radiobutton.toggled.connect(self.on_radio_button_toggled)
		layout.addWidget(radiobutton, 0, 2)

def on_radio_button_toggled(self):
	radiobutton = self.sender()
	if radiobutton.isChecked():
		print("Selected country is %s" % (radiobutton.country))