You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Qt Designer中为主窗口内的提升子部件设置快捷键?

Qt Designer无代码实现子部件搜索栏快捷键聚焦问题

父级QMainWindow包含菜单栏,子级QWidget已提升为ChildWidget,该子部件带有搜索栏。希望设置Ctrl+F快捷键,触发MainWindow.childWidget.searchBar.setFocus()来聚焦搜索栏。

已尝试的方法

  • 在部件上创建QAction:未被“使用”时无法在信号槽编辑器中生效;且QWidget无法添加QMenuBar或QToolBar,导致QAction始终处于未被使用状态,连接动作信号到槽也无法标记为已使用。
  • 将子部件提升为QMainWindow并添加QToolBar:无法完成该提升操作。
  • 定义自定义信号/槽:该功能仅支持添加部件已有的信号槽,自定义会因变量未定义报错;且父部件仅能触发子部件槽,无法让主窗口发射子部件信号。
  • 结合信号/槽/动作:在父部件定义自定义槽并连接时,若允许写入myAction.triggered.emit作为槽名可生效,但无法通过Qt Designer的验证。

备注

目前可通过代码实现该功能,但希望了解是否存在无代码方案。另外,我开发了ui2py模块用于构建UI,可在layout.ui中直接导入子ui文件进行提升,相关代码如下:

_UI_PROMOTE_TEMPLATE = """

try:
    from {mod}.{file} import {cls!s}

except ImportError:
    def {cls!s}(parent):
        import os
        import {mod}
        import ui2py
        uiDir = os.path.dirname({mod}.__file__)
        cls = ui2py.build(os.path.join(uiDir, '{file}'))

        class {cls}(QWidget, cls):
            def __init__(self, parent):
                super({cls}, self).__init__(parent)
                self.setupUi(self)
        return {cls}(parent)"""


def _fixUiPromote(code):
    """Build UI files for promotions when needed.
    The import is still attempted first as its possible there is an
    actual widget living inside of a "ui.py" file.

    Old:
        from a.b.layout.ui import MainLayout

    New:
        try:
            from a.b.layout.ui import MainLayout
        except ImportError:
            def MainLayout(parent):
                import os
                import a.b
                import ui2py
                uiDir = os.path.dirname(a.b.__file__)
                cls = ui2py.build(os.path.join(uiDir, 'layout.ui'))

                class MainLayout(QWidget, cls):
                    def __init__(self, parent):
                        super(MainLayout, self).__init__(parent)
                        self.setupUi(self)
                return MainLayout(parent)
    """
    code, replacements = re.subn(
        r'\nfrom (.*)\.([A-z][A-z0-9]*\.ui) import ([A-Z][A-z0-9]*)'.encode('utf-8'),
        lambda match: _UI_PROMOTE_TEMPLATE.format(
            mod=match.group(1).decode('utf-8'),
            file=match.group(2).decode('utf-8'),
            cls=match.group(3).decode('utf-8'),
        ).encode('utf-8'),
        code,
    )
    logger.debug('UI files promoted: %s', replacements)
    return code

内容的提问来源于stack exchange,提问作者Peter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 02:46:19