首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >生成函数,以便使用exec在pyqt中放置小部件不识别self

生成函数,以便使用exec在pyqt中放置小部件不识别self
EN

Stack Overflow用户
提问于 2016-03-15 08:32:03
回答 1查看 573关注 0票数 2

refers this question, to-convert-string-to-variable-name-in-python

我希望收集用户输入,但是由于“方法”的更改,输入字段不同,因此我希望生成基于以下内容的内容:

代码语言:javascript
复制
search_method = { 'id' : ['id'],
                  'detail' : ['catagory', 'price', 'enroll date'],
                  'drawer' : ['name', 'sex', 'state']
                  'internal' : ['transaction date', 'msg id']
                }

用作动态输入字段

预期的结果是键作为单选按钮生成,并将生成“标签”、“行编辑”对到特定的无线电选择

下面是pyqt内部的exec测试(clearLayout借用了user3369214 )

步骤:

  1. 创建小部件
  2. 创建将它们添加到布局中的函数
  3. 将信号连接到更改布局的功能

与一个接一个地添加它们相比,它的优点是扩展灵活,并且便于返回数据收集(最重要的是,短),但是程序碰巧说。

代码语言:javascript
复制
NameError: global name 'self' is not defined
or SyntaxError: can't assign to function call

可能有一些范围或内部问题,希望有人能帮忙,或一些高级功能的东西可能有帮助?

代码语言:javascript
复制
from PyQt4 import QtCore, QtGui
import sys

class TestDialog(QtGui.QDialog):
    def __init__(self, parent = None):
        super(TestDialog, self).__init__()
        self.initUI()

    def clearLayout(self, layout)
        if layout != None:
            while layout.count():
                child = layout.takeAt(0)
                if child.widget() is not None:
                    child.widget().deleteLater()
                elif child.layout() is not None:
                    self.clearLayout(child.layout())

        layout.setParent(None)

    def initUI(self):
        search_method = { 'id' : ['id'],
                          'detail' : ['catagory', 'price', 'enroll date'],
                          'drawer' : ['name', 'sex', 'state']
                          'internal' : ['transaction date', 'msg id']
                        }

        self.layTop = QtGui.QHBoxLayout()
        self.lblBy = QtGui.QLabel("By")
        self.layTop.addWidget(self.lblBy)

        for option in search_method.keys():
            exec('self.rad_' + option + ' = QtGui.QRadioButton("' + option + '")')
            exec('self.layTop.addWidget(self.rad_' + option + ')')

        self.vlay = QtGui.QHBoxLayout()
        self.vlay.addLayout(self.layTop)
        self.layInput = QtGui.QVBoxLayout()

        for option in search_method.keys():
            code =  'def by_' + option + '():'

            code += 'self.clearLayout(self.layInput)'

            for input_field in search_method[option]:
                code +=  'self.lay_' + input_field + ' = QtGui.QHBoxLayout()'
                code += ';self.lbl_' + input_field + ' = QtGui.QLabel("' + input_field + '")'
                code += ';self.edit_' + input_field + ' = QtGui.QLineEdit()'

                code += ';self.lay_' + input_field + '.addWidget(self.lbl_' + input_field + ')'
                code += ';self.lay_' + input_field + '.addWidget(self.edit_' + input_field + ')'
                code += ';self.layInput.addLayout(self.lay_' + input_field + ')'

            exec code

        for option in options.keys():
            exec('self.rad_' + option + '.toggled.connect(by_' + option + ')')

        self.setLayout(self.vlay)

app = QtGui.QApplication(sys.argv)
testDialog = TestDialog()
testDialog.show()
sys.exit(testDialog.exec_())

我也在普通课上做过测试,但效果很好(可以识别“自我”)

代码语言:javascript
复制
class A:
    def __init__(self, parm1, parm2):
        self.parm1 = parm1
        self.parm2 = parm2

    def display(self):
        to_exec = ''
        to_exec += 'def jack():'
        to_exec += 'print "hey hey hey"'
        exec(to_exec)

        exec('print self.parm' + '1')
        exec('print self.parm' + '2')
        exec('jack()')

    def aha(self):
        exec(self.display()')

a = A('hello', 'world')
exec 'a.aha()'
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-15 09:36:58

exec是不必要的。这样代码就更难读了。使用字典来保存小部件怎么样?

代码语言:javascript
复制
import sys

from PyQt4 import QtGui


class TestDialog(QtGui.QDialog):
    def __init__(self, parent=None):
        super(TestDialog, self).__init__(parent)
        self.initUI()

    def clearLayout(self, layout):
        if layout is None:
            return
        while layout.count():
            child = layout.takeAt(0)
            if child.widget() is not None:
                child.widget().deleteLater()
            elif child.layout() is not None:
                self.clearLayout(child.layout())

        layout.setParent(None)

    def initUI(self):
        search_method = {
            'id': ['id'],
            'detail': ['catagory', 'price', 'enroll_date'],
            'drawer': ['name', 'sex', 'state'],
            'internal': ['transaction_date', 'msg_id'],
        }

        self.layTop = QtGui.QHBoxLayout()
        self.lblBy = QtGui.QLabel("By")
        self.layTop.addWidget(self.lblBy)
        self.radios = {}
        self.layouts = {}
        self.labels = {}
        self.edits = {}

        for option in search_method:
            r = self.radios[option] = QtGui.QRadioButton(option)
            self.layTop.addWidget(r)

        self.vlay = QtGui.QHBoxLayout()
        self.vlay.addLayout(self.layTop)
        self.layInput = QtGui.QVBoxLayout()

        def by_option(option):
            self.clearLayout(self.layInput)
            for input_field in search_method[option]:
                lbl = self.labels[input_field] = QtGui.QLabel(input_field)
                edit = self.edits[input_field] = QtGui.QLineEdit()
                layout = self.layouts[input_field] = QtGui.QHBoxLayout()
                layout.addWidget(lbl)
                layout.addWidget(edit)
                self.layInput.addLayout(layout)
            self.vlay.addLayout(self.layInput)

        for option in search_method:
            self.radios[option].toggled.connect(
                lambda yesno, option=option: by_option(option)
            )

        self.setLayout(self.vlay)


app = QtGui.QApplication(sys.argv)
testDialog = TestDialog()
testDialog.show()
sys.exit(testDialog.exec_())
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36006049

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档