在 PyQt 布局中循环小部件 [英] Loop over widgets in PyQt Layout

查看:53
本文介绍了在 PyQt 布局中循环小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题与在 PyQT 中获取布局的小部件有些相关,但是它不是重复的.我不是在寻找如何做到这一点的高级战略观点,而是试图了解最惯用和最直接的方法是什么.由于 PyQt 是 Qt C++ API 的非常精确的绑定,因此它提供了一种 C-ish 方式来获取布局中的小部件.这是我一直在使用的那种习语:

My question is somewhat related to Get a layout's widgets in PyQT but it's not a duplicate. Instead of looking for a high level strategic view of how to do it, I'm trying to understand what the most idiomatic and straightforward way to do it would be. Since PyQt is a pretty exact binding of the Qt C++ API, it presents a C-ish way to get at widgets in a layout. Here is the sort of idiom I have been using:

for i in range(layout.count()):
  item = layout.itemAt(i)
  if type(item) == QtGui.QLayoutItem:
    doSomeStuff(item.layout())
  if type(item) == QtGui.QWidgetItem:
doSomething(item.widget())

我不是最有经验的 Python 人,但这似乎有点不符合 Python 标准.我的直觉告诉我,在理想的世界中,Python 代码应该看起来更像:

I'm not the most experienced Python guy, but this seems somewhat unpythonic. My intuition is telling me that in an ideal world, the Python code should look something more like:

for w in layout.widgets():
  doSomething(w)

我错了吗?我错过了一个高级成语吗?这是在 PyQt 中迭代小部件的最佳方法吗?我倾向于用 C++ 思考,所以我有时会错过明显"的 Python 语言特性,这些特性使事情变得更好.我正在做的部分工作是递归下降到带有布局的小部件和带有布局的小部件(等等...),以在运行时自动连接到在 Designer 中创建的 UI 的连接.添加QTabWidgets,处理设计器中设置的动态属性,我的代码基本可以工作,但感觉非常笨重.

Am I wrong? Am I missing a superior idiom? Is this the best possible way to iterate over widgets in PyQt? I tend to think in C++, so I sometimes miss out on "obvious" Python language features that make things better. Part of what I'm doing is recursively descending into widgets with layouts with widgets with layouts (etc...) to automatically wire up connections to UI's made in Designer at run time. Add in QTabWidgets, and handling of the dynamic properties set in designer, and my code basically works, but it just feels horribly clunky.

推荐答案

您可以像这样将小部件放入生成器中:

You could put the widgets into a generator like so:

items = (layout.itemAt(i) for i in range(layout.count())) 
for w in items:
   doSomething(w)

如果你经常使用它,你可以将该代码放入生成器函数中:

If you end up using that a lot, you could sock that code into a generator function:

def layout_widgets(layout):
   return (layout.itemAt(i) for i in range(layout.count()))


for w in layout_widgets(layout):
   doSomething(w)

这篇关于在 PyQt 布局中循环小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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