pyside6基础
基本结构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 import randomimport sysfrom PySide6 import QtCore, QtWidgetsclass MyWidget (QtWidgets.QWidget): def __init__ (self, *args, **kwargs ): super ().__init__(*args, **kwargs) self.hello = ["你好世界" , "Hallo Welt" , "Hei maailma" , "Hola Mundo" , "Привет мир" ] self.resize(800 , 600 ) self.button = QtWidgets.QPushButton("点击我!" ) self.text = QtWidgets.QLabel("Hello World" , alignment=QtCore.Qt.AlignCenter) self.layout = QtWidgets.QVBoxLayout(self) self.layout.addWidget(self.text) self.layout.addWidget(self.button) self.button.clicked.connect(self.magic) @QtCore.Slot() def magic (self ) -> None : """槽函数""" self.text.setText(random.choice(self.hello)) if __name__ == "__main__" : app = QtWidgets.QApplication(sys.argv) widget = MyWidget() widget.show() sys.exit(app.exec ())
基本属性
窗口和控件
QWidget是所有控件的基类,当不传入父控件时,则单独为窗口,即在传入的QWidget下创建控件,默认就是桌面
控件都是矩形的,且根据创建顺序按照Z轴排列
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 import sysfrom PySide6 import QtWidgetsclass MyWidget (QtWidgets.QWidget): def __init__ (self ): super ().__init__() self.setWindowTitle("QWidget简介" ) self.resize(800 , 600 ) self.setup_ui() def setup_ui (self ) -> None : """设置界面""" red = QtWidgets.QWidget(self) red.resize(100 , 100 ) red.setStyleSheet("background-color: red;" ) red.move(300 , 100 ) green = QtWidgets.QWidget(self) green.resize(100 , 100 ) green.setStyleSheet("background-color: green;" ) green.move(300 , 150 ) if __name__ == "__main__" : app = QtWidgets.QApplication([]) window = MyWidget() window.show() sys.exit(app.exec ())
大小和尺寸
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 .resize(800 , 600 ) .setMaximumSize(1000 , 800 ) .setMinimumSize(200 ,160 ) .setMaximumWidth(1000 ) .setMaximumHeight(800 ) .setFixedSize(500 , 500 ) .setFixedWidth(500 ) .setFixedHeight(500 ) .adjustSize()
位置
左上角为原点,向右为x轴正方向,向下为y轴正方向
为窗口时设置获取的是相对窗口的位置
为控件时设置获取的是相对父控件的位置
1 2 3 4 5 6 7 8 .move(x,y) .setGeometry(x,y,w,h) .pos() .geometry()
内容边距
实际上为css中的padding,调整实际内容和控件的边缘距离
1 2 3 4 .setContentsMargins(left,top,right,bottom) .contentsMargins()
父子控件
通过多种API来获取控制父子控件
1 2 3 4 5 6 7 8 9 10 11 12 .setParent(QWidget) .parentWidget() .children() .childAt(x,y) .childrenRect() .childrenRegion()
可见和可用
设置控件不可见后,控件原先的位置依然会被占据
按钮,下拉框,文本输入框设置为不可用后无法交互
1 2 3 4 5 6 7 8 9 10 11 12 13 .setVisible(bool ) .isVisible() .hide() .show() .setEnabled(bool ) .isEnable()
层级关系
默认后绘制的控件在上
1 2 3 4 5 6 .lower() .raise_() .stackUnder(QWidget)
焦点控制
获得了焦点的控件才可以与用户交互
可以使用TAB键在控件间移动焦点,可以指定获取的先后顺序
本控件焦点控制
1 2 3 4 5 6 .hasFocus() -> bool .setFocus(reason: Qt.FocusReason) .clearFocus()
子控件焦点控制
1 2 3 4 5 6 .focusNextChild() -> bool .focusPreviousChild() -> bool .focusNextPrevChild(next : bool ) -> bool .focusWidget() -> QWidget
Qt.FocusReason
Constant
Value
Description
Qt::MouseFocusReason
0
鼠标活动导致
Qt::TabFocusReason
1
按下了Tab键
Qt::BacktabFocusReason
2
Backtab导致,例如按下Shift+Tab键
Qt::ActiveWindowFocusReason
3
窗口系统使该窗口处于活动或非活动状态
Qt::PopupFocusReason
4
应用程序打开/关闭一个弹出窗口,该弹出窗口抓取/释放键盘焦点
Qt::ShortcutFocusReason
5
用户输入了一个标签的伙伴快捷键(参阅QLabel.buddy)
Qt::MenuBarFocusReason
6
菜单栏获得了焦点
Qt::OtherFocusReason
7
其他原因
焦点策略
切换焦点为setFocusPolicy方法
对于QPushButton、QTextEdit等控件的默认策略为StrongFocus,即可以通过键盘Tab键和鼠标点击两种方式获得焦点
对于QLabel等不需要与用户进行键盘输入交互的控件,焦点策略为NoFocus,不加入焦点链
焦点链默认顺序为子控件创建顺序,即按下键盘Tab键时会按子控件创建顺序依次切换焦点
焦点链默认顺序为子控件创建顺序,即按下键盘Tab键时会按子控件创建顺序依次切换焦点
.setTabOrder(fist: QWidget, second: QWidget) 将第二个控件从焦点链中移除,并放置到第一个控件之后
Qt::TabFocus
通过键盘Tab键获取焦点
Qt::ClickFocus
通过鼠标点击获取焦点
Qt::StrongFocus
通过键盘Tab或鼠标点击获取焦点
Qt::WheelFocus
在StrongFocus基础上,还支持鼠标滚轮滚动获取焦点
Qt::NoFocus
该控件不接受焦点,QLabel等不需要用户键盘操作的控件的默认值
光标
1 2 3 4 5 6 QWidget.setCursor(QCursor) QWidget.unsetCursor() QWidget.cursor() -> QCursor
QCursor 类的常用方法:
1 2 3 4 5 6 7 8 QCursor.__init__(shape: Qt.CursorShape) QCursor.__init__(pixmap: Union [QPixmap, QImage, str ], hotX: int = -1 , hotY: int = -1 ) QCursor.pos() -> QPoint QCursor.setPos(QPoint)
光标样式
Constant
Value
Description
Qt::ArrowCursor
0
The standard arrow cursor.
Qt::UpArrowCursor
1
An arrow pointing upwards toward the top of the screen.
Qt::CrossCursor
2
A crosshair cursor, typically used to help the user accurately select a point on the screen.
Qt::WaitCursor
3
An hourglass or watch cursor, usually shown during operations that prevent the user from interacting with the application.
Qt::IBeamCursor
4
A caret or ibeam cursor, indicating that a widget can accept and display text input.
Qt::SizeVerCursor
5
A cursor used for elements that are used to vertically resize top-level windows.
Qt::SizeHorCursor
6
A cursor used for elements that are used to horizontally resize top-level windows.
Qt::SizeBDiagCursor
7
A cursor used for elements that are used to diagonally resize top-level windows at their top-right and bottom-left corners.
Qt::SizeFDiagCursor
8
A cursor used for elements that are used to diagonally resize top-level windows at their top-left and bottom-right corners.
Qt::SizeAllCursor
9
A cursor used for elements that are used to resize top-level windows in any direction.
Qt::BlankCursor
10
A blank/invisible cursor, typically used when the cursor shape needs to be hidden.
Qt::SplitVCursor
11
A cursor used for vertical splitters, indicating that a handle can be dragged horizontally to adjust the use of available space.
Qt::SplitHCursor
12
A cursor used for horizontal splitters, indicating that a handle can be dragged vertically to adjust the use of available space.
Qt::PointingHandCursor
13
A pointing hand cursor that is typically used for clickable elements such as hyperlinks.
Qt::ForbiddenCursor
14
A slashed circle cursor, typically used during drag and drop operations to indicate that dragged content cannot be dropped on particular widgets or inside certain regions.
Qt::OpenHandCursor
17
A cursor representing an open hand, typically used to indicate that the area under the cursor is the visible part of a canvas that the user can click and drag in order to scroll around.
Qt::ClosedHandCursor
18
A cursor representing a closed hand, typically used to indicate that a dragging operation is in progress that involves scrolling.
Qt::WhatsThisCursor
15
An arrow with a question mark, typically used to indicate the presence of What’s This? help for a widget.
Qt::BusyCursor
16
An hourglass or watch cursor, usually shown during operations that allow the user to interact with the application while they are performed in the background.
Qt::DragMoveCursor
20
A cursor that is usually used when dragging an item.
Qt::DragCopyCursor
19
A cursor that is usually used when dragging an item to copy it.
Qt::DragLinkCursor
21
A cursor that is usually used when dragging an item to make a link to it.
Qt::BitmapCursor
24
按钮控件
提供按钮类通用的方法,如设置文字图标、被点击、键盘快捷键等
自身不能被实例化,子类可以被实例化
被 QPushButton、QRadioButton、QCheckBox 等类继承
1 2 3 4 5 6 7 8 9 10 11 12 13 14 class MyButton (QtWidgets.QAbstractButton): """自定义的按钮控件,体验从按钮抽象基类继承""" def paintEvent (self, evt ) -> None : """重写了父类的paintEvent""" painter = QtGui.QPainter(self) pen = QtGui.QPen(QtGui.QColor(20 , 154 , 151 ), 5 ) painter.setPen(pen) painter.drawText(20 , 70 , self.text()) painter.drawEllipse(5 , 5 , 100 , 120 )
按钮事件
clicked 光标在按钮上时按下鼠标主键,并在不离开按钮前提下抬起,才发射本信号
pressed 按下按钮时触发
released 松开按钮时触发
toggled 按钮状态改变时触发(单选按钮、复选框等)
自动重复
即按住按钮不松触发的频率
1 2 3 4 5 6 7 8 9 10 11 12 13 .setAutoRepeat(bool ) .setAutoRepeatDelay(int ) .setAutoRepeatInterval(int ) .autoRepeat() -> bool .autoRepeatDelay() -> int .autoRepeatInterval() -> int
快捷键
1 2 3 4 5 6 7 8 .setShortcut(QKeySequence) button_2.setShortcut(QtGui.QKeySequence(Qt.CTRL + Qt.Key_A)) button_1 = QtWidgets.QPushButton("&button1" , self) .shortcut() -> QKeySequence
排他性
设置排他性后选择一个单选按钮会取消其他复选框
1 2 3 4 .setAutoExclusive(bool ) .autoExclusive() -> bool
创建方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 QPushButton(parent = None ) QPushButton(text[, parent = None ]) QPushButton(icon : QIcon | QPixmap, text[, parent = None ]) QtGui.QIcon(filename : str ) button.setParent(self) button.setText("普通按钮" ) button.setIcon(icon)
扁平化
设置扁平化后,除非按钮被按下,大部分样式不会绘制按钮背景,实现视觉上的扁平化
1 2 3 4 .setFlat(bool ) .isFlat() -> bool
菜单按钮
可以将普通按钮添加菜单而使其成为菜单按钮,一个按钮可以实现多个功能
1 2 3 4 5 6 .setMenu(menu: QMenu) .Menu() -> QMenu .showMenu()
默认按钮与自动默认
default 属性设置为 true 的按钮(即对话框的默认按钮)将在用户按下 Enter 时自动被按下
如果 autoDefault 按钮当前具有焦点,则按下 autoDefault 按钮
当对话框有 autoDefault 按钮但没有默认按钮时,按 Enter 将按下当前具有焦点的 autoDefault 按钮,或者如果没有按钮具有焦点,则按下焦点链中的下一个 autoDefault 按钮
1 2 3 4 5 6 7 8 .setDefault(bool ) .isDefault() -> bool .setAutoDefault(bool ) .autoDefault() -> bool
默认开启排他性,即在一个按钮组中,只能同时有一个单选按钮被选中
属于同一个父控件的多个单选按钮,有排他性
创建方式
1 2 QRadioButton(text: str , parent: QWidget=None ) QRadioButton(parent: QWidget=None )
常用于控制单选按钮的互斥性:同组内的按钮间互斥,不同组的间互不影响
1 2 3 4 5 6 .__init__(self, parent: Optional [QObject] = None ) .addButton(button: QAbstractButton, id : int = -1 ) .removeButton(button: QAbstractButton)
复选框 QCheckBox
创建方式
复选框一般有两种选中状态(选中/未选中),有时则是三种(全部选中/部分选中/未选中)用于让用户勾选/取消勾选某些选项等
复选框默认没有排他性,也可以通过QButtonGroup分组后用setAutoExclusive()方法开启
1 2 3 .__init__(self, parent: Optional [PySide6.QtWidgets.QWidget] = None ) .__init__(self, text: str , parent: Optional [PySide6.QtWidgets.QWidget] = None )
选中状态
1 2 3 4 5 6 7 8 .setTristate(y: bool = True ) .isTristate() -> bool .setCheckState(state: Qt.CheckState) .checkState() -> Qt.CheckState
Qt.CheckState
Constant
Value
Description
Qt::Unchecked
0
未选中
Qt::PartiallyChecked
1
部分选中
Qt::Checked
2
已选中
当状态被改变时,会发出QCheckBox.stateChanged信号,Qt.CheckState的value值,可传输connect一个槽函数进行处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 def test_01 (self ) -> None : """测试信号""" @QtCore.Slot(int ) def test_slot (state: int ) -> None : print (self.cb.stateChanged) if state == 2 : print ("复选框被选中了!" ) elif state == 0 : print ("复选框被取消选中了!" ) elif state == 1 : print ("复选框被部分选中!" ) self.cb.stateChanged.connect(test_slot)
单行文本编辑器QLineEdit
创建方式
用户可以输入单行文本。适用于输入用户名等场景。
如需输入多行文本、富文本,请使用QTextEdit控件。
默认自动支持常见键盘操作,如移动光标、Home/End、复制粘贴等
1 2 .__init__(self, arg__1: str , parent: Optional [QWidget] = None ) .__init__(self, parent: Optional [QWidget] = None )
创建后设置文本
1 line_edit.setText("QLineEdit" )
显示模式
默认显示模式为正常,即用户输入什么就显示什么
也可以通过设置输入模式,使用户的输入被隐藏,常用于输入密码的场景
改变显示模式不会影响编辑器中真实存储的文字,仍可正常获取
1 2 3 4 .setEchoMode(QLineEdit.EchoMode) .echoMode() -> QLineEdit.EchoMode
Constant
Value
Description
QLineEdit::Normal
0
按字符输入时的形式显示。默认值
QLineEdit::NoEcho
1
不显示任何内容。常见场景:密码的长度也需要被保护,例如Linux输入密码
QLineEdit::Password
2
显示时用平台决定的密码掩码字符替代真实输入的字符
QLineEdit::PasswordEchoOnEdit
3
当字符正在被编辑时显示,否则行为与Password相同
1 2 3 4 .text() -> str .displayText() -> str
长度限制
单行文本编辑器可以限制用户输入的最大字符长度。
如果长度超出限制则会被在max处截断。
如果设置了掩码(见本目录其他文档),则长度由掩码限制
1 2 3 4 .setMaxLength(length: int ) .maxLength() -> int
占位文本
可以在用户未输入任何内容时设置一个占位文本,起到提示作用,
例如“在此处输入用户名”。当用户开始编辑时消失。
1 2 3 4 .setPlaceholderText(text: str ) .placeholderText() -> str
只读模式
可以开启只读模式,用户无法编辑其中的内容,与不可用(QWidget.setEnabled(False))的区别在于:
用户仍然可以复制其中的文本到剪切板、拖动文本等。
在只读模式下,不会显示光标。
1 2 3 4 .setReadOnly(yes: bool ) .isReadOnly() -> bool
文本边距
设置文字与编辑器边界间的内边距
1 2 3 4 5 .setTextMargins(left: int , top: int , right: int , bottom: int ) .setTextMargins(margins: QMargins) .textMargins() -> QMargins
对齐方式
1 2 3 4 .setAlignment(flag: Qt.Alignment) .alignment() -> Qt.Alignment
Qt.AlignmentFlag
在PySide6.QtCore.Qt.AlignmentFlag中,对齐方式主要分为:
水平对齐
Constant
Description
Qt.AlignLeft
Aligns with the left edge.
Qt.AlignRight
Aligns with the right edge.
Qt.AlignHCenter
Centers horizontally in the available space.
Qt.AlignJustify
Justifies the text in the available space
垂直对齐
Constant
Description
Qt.AlignTop
Aligns with the top.
Qt.AlignBottom
Aligns with the bottom.
Qt.AlignVCenter
Centers vertically in the available space.
Qt.AlignBaseline
Aligns with the baseline.
居中对齐
Constant
Description
Qt.AlignCenter
Centers in both dimensions.
文本边框
默认情况下,line edit会绘制一个边框,也可以通过代码设置取消
1 2 3 4 .setFrame(yes: bool ) .hasFrame() -> bool
文本编辑
通过槽函数进行复制、粘贴等操作操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 .clear() .copy() .cut() 读模式 .paste() .undo() .redo() .selectAll() .setText(text: str )
其他操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 .home(mark: bool ) .end(mark: bool ) .del_() .backspace() .isRedoAvailable() .isUndoAvailable() .setDragEnabled(b: bool ) .dragEnabled() -> bool .setClearButtonEnabled(enable: bool ) .isClearButtonEnabled() -> bool .setModified(yes: bool ) .isModified() -> bool
选中文本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 .hasSelectedText() .selectedText() .selectionStart() .selectionEnd() .selectionLength() .setSelection(start: int , length: int ) .deselect()