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

2024-02-04

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

当用户单击名为“connect”的按钮时,我想在“shost”字符串中获取带有对象名“host”的 lineedit 中的文本。我怎样才能做到这一点?我尝试过但失败了。我该如何实现这个功能呢?

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_()

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


我的第一个建议是使用 Qt Designer 来创建 GUI。自己输入它们很糟糕,需要更多时间,而且肯定会比 Qt Designer 犯更多错误。

这里有一些PyQt 教程 https://web.archive.org/web/20130704101140/http://www.diotavelli.net/PyQtWiki/Tutorials帮助您走上正轨。列表中的第一个是您应该开始的地方。

确定哪些方法可用于特定类的一个很好的指南是PyQt4 类参考 http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/classes.html。在这种情况下,你会查找QLineEdit看到有一个text method.

回答您的具体问题:

要使 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_()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当在字符串中按下 QpushButton 时,如何在 QlineEdit 中获取文本? 的相关文章

随机推荐