当前位置: 首页 > article >正文

pyside6学习专栏(一)常用控件的使用(非QML方式)

前段业余时间在用python+pyqt5边学边作一些小程序,总算作到了一个相对复杂的基本VTK三维显示地形图并计算挖填方工程量,作完后,又发现pyqt又是要收费的,就又看了下对应的替代库pyside6,对用此库的一些基本技能分享到此专栏中,此示例代码源自官方,对代码进行了整理和注解,增加了一些控件的信号槽方法示例

示例运行界面如下:

此示例代码如下

# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#模块名:mainWindow.py
#本示例代码来自pyside6官方,luowei对代码进行了注解和增加了一些控件的信号槽函数
#此代码可作为学习pyside6界面的一个示例范本

from __future__ import annotations
import sys,os,time,math,copy,random
import enum
import typing

import PySide6
from PySide6 import *
from PySide6.QtWidgets import *
from PySide6.QtCore import *
#from PySide6.QtGui import *   #如果运行时没有任何界面调出,也不报错,请屏蔽此行,原因不详
import PySide6.QtCharts

from PySide6.QtCore import Signal, QEvent,Property, QSize
from PySide6.QtCore import (QDateTime, QFile,QDir, QLibraryInfo, QSysInfo, Qt,
                            QTimer, Slot, qVersion, QAbstractTableModel, QModelIndex,
                            QPoint, QPointF,QStandardPaths, QUrl, QIODevice, QRectF,qFatal, qWarning)

from PySide6.QtGui import (QCursor, QDesktopServices, QGuiApplication, QIcon,
                           QKeySequence, QShortcut, QStandardItem,QStandardItemModel)
from PySide6.QtGui import QSurfaceFormat,QColor
from PySide6.QtGui import (QColor, QFont, QGradient, QImage, QMatrix4x4,
                           QPainter, QPlatformSurfaceEvent, QSurface, QWindow)
from PySide6.QtGui import (QRhi, QRhiBuffer,
                           QRhiDepthStencilClearValue,
                           QRhiGraphicsPipeline, QRhiNullInitParams,
                           QRhiGles2InitParams, QRhiRenderBuffer,
                           QRhiSampler, QRhiShaderResourceBinding,
                           QRhiShaderStage, QRhiTexture,
                           QRhiVertexInputAttribute, QRhiVertexInputBinding,
                           QRhiVertexInputLayout, QRhiViewport,
                           QShader)

from PySide6.QtWidgets import (QDialog,QWidget, QFileDialog, QMainWindow, QMessageBox)
from PySide6.QtWidgets import (QApplication, QCheckBox, QComboBox,
                               QCommandLinkButton, QDateTimeEdit, QDial,
                               QDialog, QDialogButtonBox, QFileSystemModel,
                               QGridLayout, QGroupBox, QHBoxLayout, QLabel,
                               QLineEdit, QListView, QMenu, QPlainTextEdit,
                               QProgressBar, QPushButton, QRadioButton,
                               QScrollBar, QSizePolicy, QSlider, QSpinBox,
                               QStyleFactory, QTableWidget, QTabWidget,
                               QTextBrowser, QTextEdit, QToolBox, QToolButton,
                               QTreeView, QVBoxLayout)

from PySide6.QtPdf import QPdfBookmarkModel, QPdfDocument
from PySide6.QtPdfWidgets import QPdfView

from PySide6.QtQuick3D import QQuick3D, QQuick3DTextureData
from PySide6.QtQml import QmlElement,QQmlApplicationEngine

from PySide6.QtCore import (QEvent, QFile, QIODevice, QPointF, QRectF, QSize,
                            qFatal, qWarning, Qt)

from PySide6.support import VoidPtr
#定义一字典,将部分可用的控件要用的数据存于此字典中
dic_ResDatas={'lst_comboSample':['选项1','选项2','选项3'],
            'lst_TableDatas':[[0,'0行0列','0行1列'],[1,'1行0列','1行1列']]
            }
EDIT_DEMOTEXT = "文本框中的内容来自全局变量EDIT_DEMOTEXT值:\n第2行内容\n第3行内容。。。。。。"
#从res文件中加载图标
DIR_OPEN_ICON = ":/qt-project.org/styles/commonstyle/images/diropen-128.png"

COMPUTER_ICON = ":/qt-project.org/styles/commonstyle/images/computer-32.png"
#得到系统信息以便在界面中的一个TAB页面中显示
SYSTEMINFO = """<html><head/><body>
<h3>Python</h3><p>{}</p>
<h3>Qt Build</h3><p>{}</p>
<h3>Operating System</h3><p>{}</p>
<h3>Screens</h3>
{}
</body></html>"""

#得到指定控件的类名称
def class_name(o):
    return o.metaObject().className()

#设置一个Qt帮助按纽的URL链接地址
#绑定了【F1】快捷键或单击【help】按纽
def help_url(page):
    major_version = qVersion().split('.')[0]
    return f"https://doc.qt.io/qt-{major_version}/{page}.html"
#按【F1】键盘后打开帮助链接窗口
def launch_help(widget):
    url = help_url(class_name(widget).lower())
    QDesktopServices.openUrl(url)

#初始化窗体的控件:每个控件均调用此全局函数来初始化
#传入的控件对象如不是self类成员变量,可以创建成功和有限的使用其属性值(信号槽直接操作的),如果不需要引用控件的值,可以不用self.,
#如果要经常性的访问问此控件对象属性值,则需要定义为self.
#参数w:控件对象     name: 对象的名称    objTypeInof:控件的tooltip信息值 bVisible:控件创建后是否可见    bEnable:控件创建后是否有效
def init_widget(w, name,objTypeInof,bVisible=True,bEnable=True):   
    w.setObjectName(name)
    w.setToolTip(objTypeInof)
    if(not bVisible):
        w.setVisible(bVisible)
    if(not bEnable):
        w.setEnabled(bEnable)
#定义加入到组给框的项目内容
def getCombolist():
    result = dic_ResDatas.get('lst_comboSample',['未得到数据时的默认值'])
    return result

#将输入类型控件加入到一个QWidget子窗体中,再将此子窗口加入到分组框中,达到分组效果
def embed_into_hbox_layout(obj, margin=5):
    parentWin = QWidget()
    layout = QHBoxLayout(parentWin)    #水平布局,将控件加入水平布局,用于使控件可以同窗体同步缩放
    layout.setContentsMargins(margin, margin, margin, margin)  #设置控件的边距
    layout.addWidget(obj)
    return parentWin                  #返回布局的父窗口对象

#指定控件的创建位置
def format_geometry(rect):
    w = rect.width()
    h = rect.height()
    x = rect.x()
    y = rect.y()
    return f"{w}x{h}{x:+d}{y:+d}"

#得到当前显示屏的信息,在一编辑框控件中显示出来
def screen_info(widget):
    policy = QGuiApplication.highDpiScaleFactorRoundingPolicy()
    policy_string = str(policy).split('.')[-1]
    result = f"<p>High DPI scale factor rounding policy: {policy_string}</p><ol>"
    for screen in QGuiApplication.screens():
        current = screen == widget.screen()
        result += "<li>"
        if current:
            result += "<i>"
        name = screen.name()
        geometry = format_geometry(screen.geometry())
        dpi = int(screen.logicalDotsPerInchX())
        dpr = screen.devicePixelRatio()
        result += f'"{name}" {geometry} {dpi}DPI, DPR={dpr}'
        if current:
            result += "</i>"
        result += "</li>"
    result += "</ol>"
    return result

#主窗口类(继承自QDialog)
class myMainWindow(QDialog):
    def __init__(self):
        super().__init__()

        self.setWindowIcon(QIcon(':/qt-project.org/logos/pysidelogo.png'))
        self._progress_bar = self.create_progress_bar()   #创建进度条控件

        self.combobox1 = QComboBox()   #原代码没有用self,现加了self,目的是在逻辑代码中好直接对此控件对象进行操作处理,仅作一个示例,其他控件同理
        init_widget(self.combobox1, "combobox1","QComboBox控件:self.combobox1")       
        self.combobox1.addItems(getCombolist())       #调用外部函数得到一构成组合框内容的列表

        style_label = QLabel("类型:")
        init_widget(style_label, "style_label","QLabel控件:style_label")
        style_label.setBuddy(self.combobox1)

        help_label = QLabel("按下快捷键【F1】在浏览器中打开一个文档")
        init_widget(help_label,"help_label", "QLabel控件:help_label")

        disable_widgets_checkbox = QCheckBox("使窗口中的全部控件失效")
        init_widget(disable_widgets_checkbox,"disable_widgets_checkbox","QCheckBox控件:disable_widgets_checkbox")

        #将窗体分成上下左右四块,每块创建一个组框,在组框中添加控件
        buttons_groupbox = self.create_groupBox_buttons()  #创建控件组框1:按纽控件组
        tabwidget_itemView = self.creat_tabWidgets()       #创建tab多页控件    
        group_Inputs = self.creat_groupBox_inputs()        #创建组框:输入控件组
        text_toolbox = self.createt_toolBox_edits()        #创建组框(属性组界面样式):编辑框组                             

        self.combobox1.textActivated.connect(self.slotComboChg)                    #下拉组合框选择项发生变化时的信号textActivated->槽函数self.slotComboChg
        disable_widgets_checkbox.toggled.connect(buttons_groupbox.setDisabled)     #复选框disable_widgets_checkbox被单击时将其他相关控件(四个组框)同步失效或有效,调用对应控件的内部槽函数
        disable_widgets_checkbox.toggled.connect(text_toolbox.setDisabled)
        disable_widgets_checkbox.toggled.connect(tabwidget_itemView.setDisabled)
        disable_widgets_checkbox.toggled.connect(group_Inputs.setDisabled)

        help_shortcut = QShortcut(self)
        help_shortcut.setKey(QKeySequence.HelpContents)           
        help_shortcut.activated.connect(self.slotHelp)        #按下【F1】键的槽函数 

        top_layout = QHBoxLayout()                            #|一行4列:竖直分布
        top_layout.addWidget(style_label)                     #|                            +addStretch     +addStretch
        top_layout.addWidget(self.combobox1)                  #|style_label   self.combobox1     help_label   disable_widgets_checkbox |
        top_layout.addStretch(1)
        top_layout.addWidget(help_label)
        top_layout.addStretch(1)
        top_layout.addWidget(disable_widgets_checkbox)

        dialog_buttonbox = QDialogButtonBox(QDialogButtonBox.Help | QDialogButtonBox.Close)   #按纽控件组【Help】+【Close】两个按纽的窗体
        init_widget(dialog_buttonbox, "dialog_buttonbox","QDialogButtonBox按纽控件组【Help】+【Close】:dialog_buttonbox")
        dialog_buttonbox.helpRequested.connect(self.slotWebHelp)    #按下【Help】键时,打开一超链接地址
        dialog_buttonbox.rejected.connect(self.reject)

        main_layout = QGridLayout(self)                                         # |--------------------50%---------------------------------------
        main_layout.addLayout(top_layout, 0, 0, 1, 2)                           #0|                 top_layout(详上面的竖直布局:1行四列四个控件)
        main_layout.addWidget(buttons_groupbox, 1, 0)                           #1|  buttons_groupbox   |   group_Inputs
        main_layout.addWidget(group_Inputs, 1, 1)                               #2|  tabwidget_itemView |   text_toolbox
        main_layout.addWidget(tabwidget_itemView, 2, 0)                         #3|  self._progress_bar |
        main_layout.addWidget(text_toolbox, 2, 1)                               #4|              dialog_buttonbox
        main_layout.addWidget(self._progress_bar, 3, 0, 1, 2)                   # |---------------------50%---------------------------------------        
        main_layout.addWidget(dialog_buttonbox, 4, 0, 1, 2)                               
                                                                                
        qv = qVersion()
        self.setWindowTitle(f"PySide6.8的常用控件示例程序{qv}")

    #重载窗体显示时的内部方法:
    def setVisible(self, visible):
        super(myMainWindow, self).setVisible(visible)
        if visible:
            self.windowHandle().screenChanged.connect(self.slotUpdateSysInfo)    #直接用窗体句柄的屏幕变化信号来调用槽函数,更新系统信息
            self.slotUpdateSysInfo()

    #创建按纽组合框中的全部控件
    def create_groupBox_buttons(self):
        btnGroupBox = QGroupBox("组合框:按纽:btnGroupBox")
        init_widget(btnGroupBox,"btnGroupBox", " QGroupBox组合框控件;")

        default_pushbutton = QPushButton("默认标准按纽")
        init_widget(default_pushbutton,"default_pushbutton","QPushButton控件:default_pushbutton")
        default_pushbutton.setDefault(True)
        default_pushbutton.clicked.connect(self.slotPushBtnClick)   #为此按纽设置单击信号的槽函数

        toggle_pushbutton = QPushButton("复选框按纽")
        init_widget(toggle_pushbutton,"toggle_pushbutton", "QPushButton控件:toggle_pushbutton")
        toggle_pushbutton.setCheckable(True)
        toggle_pushbutton.setChecked(True)

        flat_pushbutton = QPushButton("QPushButton平面按纽")
        init_widget(flat_pushbutton,"flat_pushbutton", "QPushButton控件:flat_pushbutto")
        flat_pushbutton.setFlat(True)

        toolbutton = QToolButton()
        init_widget(toolbutton, "toolbutton","QToolButton控件:toolbutton")
        toolbutton.setText("工具栏按纽")

        menu_toolbutton = QToolButton()
        init_widget(menu_toolbutton,"menu_toolbutton", "QToolButton控件:menu_toolbutton")
        menu_toolbutton.setText("菜单按纽")
        tool_menu = QMenu(menu_toolbutton)
        menu_toolbutton.setPopupMode(QToolButton.InstantPopup)
        action_opt1=tool_menu.addAction("属性",0)
        tool_menu.addSeparator()
        action_chkopt2 = tool_menu.addAction("复选属性",1)
        action_chkopt2.setCheckable(True)
        menu_toolbutton.setMenu(tool_menu)
        tool_layout = QHBoxLayout()
        tool_layout.addWidget(toolbutton)
        tool_layout.addWidget(menu_toolbutton)

        action_opt1.triggered.connect(self.slotActMenu)       #菜单选项1对应的信号槽

        commandlinkbutton = QCommandLinkButton("超链接命令按纽")
        init_widget(commandlinkbutton,"commandlinkbutton" ,"QCommandLinkButton控件:commandlinkbutton")
        commandlinkbutton.setDescription("www.360.cn")
        commandlinkbutton.clicked.connect(lambda:self.slotCmdLinkButton("www.163.com"))    #响应命令按纽的槽函数:槽参数传入一字符串,槽要传参数,注意lambda:的使用
 
        button_layout = QVBoxLayout()
        button_layout.addWidget(default_pushbutton)
        button_layout.addWidget(toggle_pushbutton)
        button_layout.addWidget(flat_pushbutton)
        button_layout.addLayout(tool_layout)
        button_layout.addWidget(commandlinkbutton)
        button_layout.addStretch(1)

        radiobutton_1 = QRadioButton("单选按纽1")
        init_widget(radiobutton_1,"radiobutton_1" ,"QRadioButton控件:radiobutton_1")
        radiobutton_2 = QRadioButton("单选按纽2")
        init_widget(radiobutton_2, "radiobutton_2","QRadioButton控件:radiobutton_2")
        radiobutton_3 = QRadioButton("单选按纽3")
        init_widget(radiobutton_3,"radiobutton_3", "QRadioButton控件:radiobutton_3")
        radiobutton_1.setChecked(True)
        radiobutton_1.toggled.connect(self.slotRadioChg)       #单选按纽状态发生变化时的信号槽

        checkbox3 = QCheckBox("三态复选框按纽")
        init_widget(checkbox3,"checkbox3", "QCheckBox控件(三态显示):checkbox3")
        checkbox3.setTristate(True)
        checkbox3.setCheckState(Qt.PartiallyChecked)
        checkbox3.stateChanged.connect(self.slotChkGetValue)     #复选框状态发生变化的信号槽

        checkable_layout = QVBoxLayout()
        checkable_layout.addWidget(radiobutton_1)
        checkable_layout.addWidget(radiobutton_2)
        checkable_layout.addWidget(radiobutton_3)
        checkable_layout.addWidget(checkbox3)
        checkable_layout.addStretch(1)

        main_layout = QHBoxLayout(btnGroupBox)
        main_layout.addLayout(button_layout)
        main_layout.addLayout(checkable_layout)
        main_layout.addStretch()
        return btnGroupBox
    
    #创建QToolBox类型组合控件
    def createt_toolBox_edits(self):
        textToolBox = QToolBox()
        init_widget(textToolBox ,"textToolBox" ,"QToolBox控件:textToolBox")

        # HTML rich文本变量值
        rich_text = "<html><head/><body><i>"
        for line in EDIT_DEMOTEXT.split('\n'):
            rich_text += f"<center>{line}</center>"
        rich_text += "</i></body></html>"

        text_edit = QTextEdit(rich_text)     
        init_widget(text_edit, "text_edit","QTextEdit控件:textEdit")
        plain_textedit = QPlainTextEdit(EDIT_DEMOTEXT)
        init_widget(plain_textedit,"plain_textedit" ,"QPlainTextEdit控件:plainTextEdit")

        self._systeminfo_textbrowser = QTextBrowser()
        init_widget(self._systeminfo_textbrowser,"_systeminfo_textbrowser" ,"QTextBrowser控件:_systeminfo_textbrowserr")

        textToolBox.addItem(embed_into_hbox_layout(text_edit), "QTextEdit控件(HTML富文本)")
        textToolBox.addItem(embed_into_hbox_layout(plain_textedit), "QPlainTextEdit控件")
        textToolBox.addItem(embed_into_hbox_layout(self._systeminfo_textbrowser), "QTextBrowser控件(显示系统信息)")
        return textToolBox 
    
    #创建一个多页TAB控件及控件中的子控件
    def creat_tabWidgets(self):
        tabWidgets = QTabWidget()
        init_widget(tabWidgets,"tabWidgets" ,"QTabWidget控件:tabWidgets")
        tabWidgets.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Ignored)

        tree_view = QTreeView()
        init_widget(tree_view,"tree_view", "QTreeView控件:tree_view")
        filesystem_model = QFileSystemModel(tree_view)
        filesystem_model.setRootPath(QDir.rootPath())
        tree_view.setModel(filesystem_model)

        table_widget = QTableWidget()
        init_widget(table_widget, "table_widget","QTableWidget控件:table_widget")
        table_widget.setRowCount(10)
        table_widget.setColumnCount(10)

        list_model = QStandardItemModel(0, 1, tabWidgets)
        list_model.appendRow(QStandardItem(QIcon(DIR_OPEN_ICON), "目录"))
        list_model.appendRow(QStandardItem(QIcon(COMPUTER_ICON), "计算机"))

        list_view = QListView()
        init_widget(list_view,"list_view" ,"QListView列表视控件:list_view")
        list_view.setModel(list_model)

        icon_mode_listview = QListView()
        init_widget(icon_mode_listview, " icon_mode_listview","QListView控件:icon_mode_listview")

        icon_mode_listview.setViewMode(QListView.IconMode)
        icon_mode_listview.setModel(list_model)

        tabWidgets.addTab(embed_into_hbox_layout(tree_view), "树视图")          #实际加入的是一QWidget窗体,Qwidget窗体上又依附了子窗体控件tree_view
        tabWidgets.addTab(embed_into_hbox_layout(table_widget), "表格视图")     #同上
        tabWidgets.addTab(embed_into_hbox_layout(list_view), "列表视图")
        tabWidgets.addTab(embed_into_hbox_layout(icon_mode_listview),"图标列表视图")
        return tabWidgets
    
    #创建简单输入框类组合框
    def creat_groupBox_inputs(self):
        inGroups = QGroupBox("简单的数据输入控件")
        init_widget(inGroups,"inGroups", "QGroupBox组合框控件:inGroups")
        inGroups.setCheckable(True)
        inGroups.setChecked(True)

        lineedit = QLineEdit("password1234")
        init_widget(lineedit, "lineedit","QLineEdit单行输入控件(密码类型):lineedit")
        lineedit.setClearButtonEnabled(True)
        lineedit.setEchoMode(QLineEdit.Password)

        spin_box = QSpinBox()
        init_widget(spin_box,"spin_box","QSpinBox微调控件:spin_box")
        spin_box.setValue(50)
        spin_box.valueChanged.connect(self.soltSpinChg)               #微调控件数值发生变化时的信号槽

        date_timeedit = QDateTimeEdit()
        init_widget(date_timeedit,"date_timeedit","QDateTimeEdit日期时间控件:date_timeedit")
        date_timeedit.setDateTime(QDateTime.currentDateTime())

        slider = QSlider()
        init_widget(slider,"slider", "QSlider微调控件:slider")
        slider.setOrientation(Qt.Orientation.Horizontal)
        slider.setValue(40)

        scrollbar = QScrollBar()
        init_widget(scrollbar,"scrollbar","QScrollBar滚动条控件:scrollbar")
        scrollbar.setOrientation(Qt.Orientation.Horizontal)
        scrollbar.setValue(60)

        dial = QDial()
        init_widget(dial,"dial","QDial圆形微调控件:dial")
        dial.setValue(30)
        dial.setNotchesVisible(True)

        #对以上控件在 简单的数据输入控件inGroups 分组范围进行网格布局分配位置
        layout = QGridLayout(inGroups)   
        #                          行 列 高占用行 宽占用列     对齐方式                                          # | -------------------------------          
        layout.addWidget(lineedit, 0, 0,    1,     2,Qt.AlignmentFlag.AlignLeft|Qt.AlignmentFlag.AlignTop)     #  |            0                 |     0行0列:lineedit点
        layout.addWidget(spin_box, 1, 0, 1, 2)                                                                 #  |            1                 |     1行0列:lineedit
        layout.addWidget(date_timeedit, 2, 0, 1, 2)                                                            #  |            2                 |
        layout.addWidget(slider, 3, 0,1,1)        #同(slider, 3, 0)                                            #  |      3     |      4(1)       |     
        layout.addWidget(dial, 3, 1,2,1)          #同(slider, 3,1,2,1)                                         #  |      3     |      4(2)       |
        layout.addWidget(scrollbar, 4, 0,1,1)     #同(slider, 4,0)                                             #  |            5                 |      5行位置无控件为但为组合框分配的一行区域
        layout.setRowStretch(5, 1)                #共计分配0-4行+1列                                            #  | -----------------------------|
        return inGroups
    
    #创建进度条控件,同时启动一计时器self.timer1
    def create_progress_bar(self):
        progbar = QProgressBar()
        init_widget(progbar,"progbar", "QProgressBar控件:progbar")
        progbar.setRange(0, 10000)
        progbar.setValue(0)

        self.timer1 = QTimer(self)
        self.timer1.timeout.connect(self.slotUpdateProgressbar)       #计时器对应的时间每间隔200毫秒调用一次指定的槽函数
        self.timer1.start(200)
        return progbar

    #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@以下为各控件的信号槽示例代码@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
    #槽方法:当下接组合框的选择项发生变化时
    #发送信号的对象:self.combobox1 = QComboBox()
    #发送信号定义:self.combobox1.textActivated.connect(self.slotComboChg) 
    @Slot(str)
    def slotComboChg(self, style_name):
        print(f'当前组合框选择项={style_name}')

    #槽方法:计时器self.timer1每200毫秒执行一次槽函数
    #发送信号的对象:self.timer1 = QTimer(self)
    #发送信号定义:self.timer1.timeout.connect(self.slotUpdateProgressbar) 
    @Slot()
    def slotUpdateProgressbar(self):
        cur_val = self._progress_bar.value()
        max_val = self._progress_bar.maximum()
        self._progress_bar.setValue(cur_val + (max_val - cur_val) / 100)
    
    #槽方法:直接用窗体句柄的屏幕变化信号来调用槽函数,更新系统信息
    #发送信号的对象:self.windowHandle()
    #发送信号定义:self.windowHandle().screenChanged.connect(self.slotUpdateSysInfo)
    @Slot()
    def slotUpdateSysInfo(self):
        #更新显示系统信息
        system_info = SYSTEMINFO.format(sys.version,
                                        QLibraryInfo.build(),
                                        QSysInfo.prettyProductName(),
                                        screen_info(self))
        self._systeminfo_textbrowser.setHtml(system_info)
    

    #槽方法:按下快捷键【F1】
    #发送信号的对象: help_shortcut = QShortcut(self)
    #发送信号定义: help_shortcut.activated.connect(self.slotHelp)      
    @Slot()
    def slotHelp(self):
        """Display help on widget under mouse"""
        w = QApplication.widgetAt(QCursor.pos(self.screen()))
        while w:  # Skip over internal widgets
            name = w.objectName()
            if name and not name.startswith("qt_"):
                launch_help(w)
                break
            w = w.parentWidget()
    
    #槽方法:按下组合按纽中的【help】按纽的槽
    #发送信号的对象: dialog_buttonbox = QDialogButtonBox(QDialogButtonBox.Help | QDialogButtonBox.Close)
    #发送信号定义:dialog_buttonbox.helpRequested.connect(self.slotWebHelp) 
    @Slot()
    def slotWebHelp(self):
        QDesktopServices.openUrl(help_url("qtwidgets-index"))

    #槽方法:单击按纽
    #发送信号的对象:default_pushbutton = QPushButton("默认标准按纽") 
    #发送信号定义:default_pushbutton.clicked.connect(self.slotPushBtnClick)
    @Slot()
    def slotPushBtnClick(self):
        QMessageBox.information(None, "信息", "单击了default_pushbutton控件")
   

    #槽方法:微调控件数值发生变化时的信号槽
    #发送信号的对象:spin_box = QSpinBox()   注意,本控件当前没有self.,也可以得到正确的交互值
    #发送信号定义:spin_box.valueChanged.connect(self.soltSpinChg)      
    @Slot(int)     
    def soltSpinChg(self,value):
        print(f'微调spin_box控件的当前值={value}')

    #槽方法:单击三态复选框时得到当前复选框的状态
    #发送信号的对象:checkbox3 = QCheckBox("三态复选框按纽")
    #发送信号定义:checkbox3.stateChanged.connect(self.slotChkGetValue)
    @Slot(int)
    def slotChkGetValue(self,value):
        print(f'三态复选框checkbox3控件的当前值={value}')

      
    #槽方法:按纽上弹菜单选单击菜单项1【属性】对应的信号槽
    #发送信号的对象:action_opt1
    #发送信号定义:action_opt1.triggered.connect(self.slotActMenu)       
    @Slot()
    def slotActMenu(self,value):
        print(f'按纽上弹菜单【属性】action_opt1当前从参数传入的值={value}')

    #槽方法:单击命令按纽的槽响应函数
    #发送信号的对象:commandlinkbutton = QCommandLinkButton("超链接命令按纽")
    #发送信号定义:commandlinkbutton.triggered.connect(lambda:self.slotCmdLinkButton("www.163.com"))    #响应命令按纽的槽函数:槽参数传入一字符串
    @Slot(str)
    def slotCmdLinkButton(self,urlStr):
         print(f'单击命令按纽信号传入槽参数的值={urlStr}')

    #槽方法:单面单选框按纽时的槽(单击它肯定是选中它,单击其他同组中的radioButton时,此槽函数仍要响应,但value值为False)
    #发送信号的对象:
    #发送信号定义:radiobutton_1.toggled.connect(self.slotRadioChg)       #单选按纽状态发生变化时的信号槽
    @Slot()
    def slotRadioChg(self,value):
         print(f'单选框控件的当前值={value}')   #value值肯定为True


#################################
#程序主入口
if __name__ == '__main__':
    app = QApplication()
    mainwin = myMainWindow()
    mainwin.show()
    sys.exit(app.exec())


http://www.kler.cn/a/428566.html

相关文章:

  • 将 AzureBlob 的日志通过 Azure Event Hubs 发给 Elasticsearch(1.标准版)
  • Observability:最大化可观察性 AI 助手体验的 5 大提示(prompts)
  • 【3GPP】【5G】注销流程(Deregistration procedures)
  • 【游戏设计原理】75 - 最小最大化
  • Java 中 HashSet 集合元素的去重
  • Linux-C/C++--深入探究文件 I/O (下)(文件共享、原子操作与竞争冒险、系统调用、截断文件)
  • dockerfile部署前后端(vue+springboot)
  • 16asm -指令
  • 2024/12/8 Windows安装Oracle19c
  • 锁相关的问题(死锁、互斥锁、自旋锁、读写锁、悲观锁、乐观锁)
  • Mac 录制电脑系统内的声音的具体方法?
  • threadcache实现细节(二)
  • Linux-V4L2摄像头应用编程
  • 安卓调试环境搭建
  • RTCMultiConnection 跨域问题解决
  • js循环导出多个word表格文档
  • OD B卷【恢复数字序列】
  • TCP客户端服务器端通信(线程池版)
  • 【机器学习】基于SVM、逻辑回归和CNN的手写数字识别:性能对比与应用分析
  • (七)腾讯cloudstudio+Stable-Diffusion-webui AI绘画教程-安装Stable-Diffusion-WebUI
  • Vue3组件通信(父传子,子传父,跨组件通信)
  • 21届秋/校招面经
  • xLSTM 阅读笔记
  • 日本IT|企业需要什么样的技术?
  • 处理后端返回的时间格式问题
  • MySQL -- CURD(下)