新手在python qt; setlayout()似乎禁止.self前缀?

时间:2013-02-15 19:11:32

标签: qt class python-2.7 pyside

我是一个蟒蛇新手/业余爱好者,希望将python编程带入我的下一个职业。 我购买并阅读了Summerfield一书中的第119页“使用Python和QT进行Rapid Gui编程”。我遇到了障碍,想知道你是否可以给我一些指导。 我的问题如下: 为什么不允许或不必插入“自我”。作为下面每个小部件之前的前缀?

例如,如果我添加前缀“self”。到“title = QtGui.QLabel('Title')”行,我收到以下错误消息:NameError:全局名称'title'未定义

我在Summerfield上的“Python gui Programming with qt4”一书中读到“setlayout()”重新编写小部件,以便Form成为父级。我认为他表示使用“setlayout()”会使前缀“.self”变得不必要。

但如果你不使用“自我”。作为前缀,你如何指向一个小部件? 例如,如果我使用setlayout将“Form”作为父级,我的函数“fn_okButton01_clicked(self):”应该能够得到“titleEdit”的文本值,但是我无法弄清楚获取文本的正确方法值。

我尝试使用“print self .titleEdit.getText()”和“print Form .titleEdit.getText()”两者都没有用。当我尝试使用后者时,错误消息是:AttributeError:'Form'对象没有属性'titleEdit' 任何指导都将非常感谢。

谢谢,

                Marc

以下是我一直在使用的代码:

# -*- coding: utf-8 -*-

import sys
from PyQt4 import QtGui
from PyQt4.QtCore import (Qt, SIGNAL)
from PyQt4.QtGui import (QApplication, QDialog, QHBoxLayout, QLabel,
        QPushButton)

class Form(QDialog):

    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        self.initUI()

    def initUI(self):

        okButton01 = QtGui.QPushButton("OK")
        cancelButton01 = QtGui.QPushButton("Cancel")
        okButton01.clicked.connect(self.fn_okButton01_clicked)

        title = QtGui.QLabel('Title')
        author = QtGui.QLabel('Author')
        review = QtGui.QLabel('Review')

        titleEdit = QtGui.QLineEdit()
        authorEdit = QtGui.QLineEdit()
        reviewEdit = QtGui.QTextEdit()

        hbox01 = QtGui.QHBoxLayout()
        hbox01.addStretch(1)
        hbox01.addWidget(title)
        hbox01.addWidget(titleEdit)

        hbox02 = QtGui.QHBoxLayout()
        hbox02.addStretch(1)
        hbox02.addWidget(author)
        hbox02.addWidget(authorEdit)

        hbox03 = QtGui.QHBoxLayout()
        hbox03.addStretch(1)
        hbox03.addWidget(review)
        hbox03.addWidget(reviewEdit)

        hbox00 = QtGui.QHBoxLayout()
        hbox00.addStretch(1)
        hbox00.addWidget(okButton01)
        hbox00.addWidget(cancelButton01)

        vbox0 = QtGui.QVBoxLayout()
        vbox0.addStretch(1)
        vbox0.addLayout(hbox01)
        vbox0.addStretch(1)
        vbox0.addLayout(hbox02)
        vbox0.addStretch(1)
        vbox0.addLayout(hbox03)
        vbox0.addStretch(1)
        vbox0.addLayout(hbox00)

        self.setLayout(vbox0)    

        self.setGeometry(300, 300, 300, 150)
        self.setWindowTitle('Data Input Fields')    
        self.show()

    def fn_okButton01_clicked(self):
        print self.titleEdit.getText()


def main():

    app = QApplication(sys.argv)
    form = Form()
    form.show()
    app.exec_()


if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:1)

您创建的对象将分配给局部变量。要在以后访问它们,您必须将它们分配给您的类的实例。例如,放置

self.titleEdit = titleEdit

在initUI函数的末尾。作为替代方案,您还可以使用

检索触发信号的对象
self.sender()