在 PyQt5 中,我们如何获取焦点小部件的名称/对象名称? [英] In PyQt5, How we get the name/Object name of the focus widgets?

查看:78
本文介绍了在 PyQt5 中,我们如何获取焦点小部件的名称/对象名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的 PyQt5 程序中,我们多次使用 Qline Edits、QcheckBox、QListwidget.

In Our PyQt5 Programme, we use Qline Edits, QcheckBox, QListwidget several times.

如何知道:

  1. 我们的程序中使用了哪些具有 Widget 名称的 Widget?
  2. 如何获取/返回当前具有焦点的小部件的名称(用户分配的名称)

推荐答案

正如@Heike 所建议的,您可以通过 QApplication.focusWidget

As @Heike suggested, you can get a reference to the widget that has focus with QApplication.focusWidget

根据您的小部件的创建方式,它们可能没有 objectName.如果您使用像 Designer 或 Creator 这样的 GUI 将小部件放在表单上,​​那么您将设置对象名称.但是,如果您在代码中创建表单,则可能根本没有设置 objectName.在这种情况下,您只需确保在代码中设置 objectName.你可以看到我的这个问题来讨论设置 objectName 但切入正题,你可以使用 objectName 作为关键字参数,当您在代码中声明您的小部件时,例如:

Depending on how your widgets are created, they might not have an objectName. If you use a GUI like Designer or Creator to drop your widgets on a form, then you will have the object name set. However, if you are creating your form in code, you may not have objectName set at all. In that case, you can just make sure to set the objectName in your code. You can see this question of mine for a discussion of setting objectName but to cut to the chase, you can use objectName as a keyword argument when you declare your widget in code, e.g.:

self.MyWidget = QWidget(objectName = MyWidget)

以及稍后如果您想获取具有焦点的小部件的名称,您将使用

and later on if you want to get name of the widget that has focus you would use

widgetname = self.focusWidget().objectName()

或者你可以对参考做一些事情:

or you could just do something with the reference:

widget = self.focusWidget()

这篇关于在 PyQt5 中,我们如何获取焦点小部件的名称/对象名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆