我想知道是否可以使用for循环设置多个setFixedHeight()
属性:
for num in range(1, 6):
self.LineEdit[num].setFixedHeight()
目前我有十二个QLineEdit框
LineEdit1,LineEdit2,...,LineEdit12和我希望用更少的代码完成此操作。我尝试了上面的方法,并没有按照我的预期迭代LineEdit框。 self.LineEdit[num]
只适用于列表吗?
答案 0 :(得分:2)
对于此任务,您可以使用getattr()
:
for i in range(1,13):
getattr(self, "LineEdit{}".format(i)).setFixedHeight(10)
答案 1 :(得分:1)
您可以使用findChildren()
功能。
e.g。
for ctl in self.findChildren(QtGui.QLineEdit):
ctl.setFixedHeight()
请注意,这会在所有线路编辑中调用setFixedHeight()
。
答案 2 :(得分:0)
带有Quamash,Coroutines和observer-pattern
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
http://code.activestate.com/recipes/131499-observer-pattern/
*TL;DR80
Maintains a list of dependents and notifies them of any state changes.
*Examples in Python ecosystem:
Django Signals: https://docs.djangoproject.com/en/2.1/topics/signals/
Flask Signals: http://flask.pocoo.org/docs/1.0/signals/
"""
from __future__ import print_function
import sys
from PyQt5.QtWidgets import (QLineEdit, QApplication, QWidget, QVBoxLayout)
import random
import asyncio
class Subject(object):
def __init__(self):
self._observers = []
def attach(self, observer):
if observer not in self._observers:
self._observers.append(observer)
def detach(self, observer):
try:
self._observers.remove(observer)
except ValueError:
pass
def notify(self, modifier=None):
for observer in self._observers:
if modifier != observer:
observer.update(self)
# Example usage
class Data(Subject):
def __init__(self, name=''):
Subject.__init__(self)
self.name = name
self._data = 0
self.default = 0
@property
def data(self):
return self._data
@data.setter
def data(self, value):
self._data = value
self.notify()
class ObservableViewer:
_line_edit = None
def __init__(self, line_edit):
self.line_edit = line_edit
@property
def line_edit(self):
return self._line_edit
@line_edit.setter
def line_edit(self, value):
self._line_edit = value
def update(self, subject):
asyncio.get_event_loop().call_soon_threadsafe(self.line_edit.setText, subject.data)
class Widget(QWidget):
layout = None
def __init__(self, parent=None):
super(QWidget, self).__init__(parent)
self.x = ['abc', 'def', 'ghi', 'jkl', 'etc']
self.dx = []
self._init_component()
asyncio.run_coroutine_threadsafe(self.update_async(), loop=asyncio.get_event_loop())
def _init_component(self):
self.layout = QVBoxLayout()
self.setLayout(self.layout)
for xi in self.x:
lei = QLineEdit()
lei.setAccessibleName(f"__{xi}")
lei.setText(xi)
di = Data(str(xi))
self.dx.append(di)
ovi = ObservableViewer(line_edit=lei)
di.attach(ovi)
di.data = xi
di.default = xi
self.layout.addWidget(lei)
@asyncio.coroutine
async def update_async(self):
while True:
for di in self.dx:
di.data = f"{di.default}-{random.randrange(0, 101, 2)}"
await asyncio.sleep(1, loop=asyncio.get_event_loop())
if __name__ == "__main__":
from quamash import (QEventLoop)
app = QApplication(sys.argv)
loop = QEventLoop(app)
asyncio.set_event_loop(loop)
w = Widget()
w.show()
sys.exit(app.exec_())