如何在字符串中按下QpushButton时在QlineEdit中获取文本?

esa*_*wan 33 python pyqt4 qlineedit

我正在尝试实现一个功能.我的代码如下.

我希望当用户点击名为"connect"的按钮时,在字符串中使用对象名称'host'的文本中的文本说'shost'.我怎样才能做到这一点?我尝试过但失败了.我该如何实现这个功能?

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *


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

        le = QLineEdit()
        le.setObjectName("host")
        le.setText("Host")
        pb = QPushButton()
        pb.setObjectName("connect")
        pb.setText("Connect") 
        layout.addWidget(le)
        layout.addWidget(pb)
        self.setLayout(layout)

        self.connect(pb, SIGNAL("clicked()"),self.button_click)

        self.setWindowTitle("Learning")

    def button_click(self):
    #i want the text in lineedit with objectname 
    #'host' in a string say 'shost'. when the user click 
    # the pushbutton with name connect.How do i do it?
    # I tried and failed. How to implement this function?




app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
Run Code Online (Sandbox Code Playgroud)

现在我该如何实现"button_click"功能?我刚开始使用pyQt!

tgr*_*ray 41

我的第一个建议是使用Designer来创建GUI.自己打字很糟糕,花费更多时间,你肯定会比设计师犯更多错误.

这里有一些PyQt教程可以帮助您走上正确的轨道.列表中的第一个是您应该从哪里开始的.

PyQt4类参考是一个很好的指南,用于确定哪些方法可用于特定类.在这种情况下,你会查找QLineEdit并看到有一种text方法.

要回答您的具体问题:

要使GUI元素可用于对象的其余部分,请在其前面加上 self.

import sys
from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import QDialog, QApplication, QPushButton, QLineEdit, QFormLayout

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

        self.le = QLineEdit()
        self.le.setObjectName("host")
        self.le.setText("Host")

        self.pb = QPushButton()
        self.pb.setObjectName("connect")
        self.pb.setText("Connect") 

        layout = QFormLayout()
        layout.addWidget(self.le)
        layout.addWidget(self.pb)

        self.setLayout(layout)
        self.connect(self.pb, SIGNAL("clicked()"),self.button_click)
        self.setWindowTitle("Learning")

    def button_click(self):
        # shost is a QString object
        shost = self.le.text()
        print shost


app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
Run Code Online (Sandbox Code Playgroud)

  • 您需要在__init__函数中将其命名为self.le。您在`Form`类中使用它的任何地方都应该是`self.le`。 (2认同)
  • shost = self.le.text() 可能会给出 QString 输出。使用 str() 对其进行转换以获得有意义的文本。 (2认同)