gpt4 book ai didi

python - 如何在 PyQt5 中获取当前聚焦的小部件对象名称?

转载 作者:行者123 更新时间:2023-12-04 09:33:00 24 4
gpt4 key购买 nike

如何在 PyQt5 中获取当前聚焦的小部件 objectName?这是我的代码。在我的代码中,我获得了所有小部件的对象名称。我也想知道重点小部件 objectName。

import sys

from PyQt5.QtWidgets import *
class Check(QWidget):

def __init__(self):
super().__init__()
self.setWindowTitle("Check Window")
self.textbox1 = QLineEdit(self)
self.textbox1.setGeometry(100, 100, 300, 30)
self.textbox2 = QLineEdit(self)
self.textbox2.setGeometry(100, 150, 300, 30)
self.textbox3 = QLineEdit(self)
self.textbox3.setGeometry(100, 200, 300, 30)

self.lbox1 = QListWidget()
self.lbox2 = QListWidget(self)
self.lbox2.setGeometry(100,250,300,500)
self.textbox1.setObjectName("textbox1")
self.textbox2.setObjectName("textbox2")
self.textbox3.setObjectName("textbox3")

self.updateallwidgets()
self.focuwidget()

def updateallwidgets(self):
QWidget.allwidgets = QApplication.allWidgets()
for i in QWidget.allwidgets:
j = i.objectName()


def focuwidget(self):
fwidget = QApplication.focusWidget()
print("focus widget name ",fwidget)

def main():
myapp = QApplication(sys.argv)
mywin = Check()
mywin.show()
sys.exit(myapp.exec_())

if __name__ == "__main__":
main()

最佳答案

您正在尝试在创建始终为 None 的窗口之前获取具有焦点的小部件,解决方案是通过 focusChanged 信号检测焦点何时发生变化:

class Check(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Check Window")
self.textbox1 = QLineEdit(self)
self.textbox1.setGeometry(100, 100, 300, 30)
self.textbox2 = QLineEdit(self)
self.textbox2.setGeometry(100, 150, 300, 30)
self.textbox3 = QLineEdit(self)
self.textbox3.setGeometry(100, 200, 300, 30)

self.lbox1 = QListWidget()
self.lbox2 = QListWidget(self)
self.lbox2.setGeometry(100, 250, 300, 500)
self.textbox1.setObjectName("textbox1")
self.textbox2.setObjectName("textbox2")
self.textbox3.setObjectName("textbox3")

QApplication.instance().focusChanged.connect(self.on_focusChanged)

def on_focusChanged(self):
fwidget = QApplication.focusWidget()
if fwidget is not None:
print("focus widget name ", fwidget.objectName())

关于python - 如何在 PyQt5 中获取当前聚焦的小部件对象名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62742104/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com