【问题标题】:PyQt4: Read texts in QLineEdit/QTextEdit and implement the text change into some functions by clicking a buttonPyQt4:读取QLineEdit/QTextEdit中的文本并通过单击按钮实现文本更改为一些功能
【发布时间】:2017-09-29 17:57:08
【问题描述】:

我想通过在小部件中输入一些文本来更改函数中的一些值。我不确定我应该使用 QLineEdit 还是 QTextEdit,因为我已经阅读了一些文档并且他们似乎都能够做到。我有一些示例代码如下。

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

class Widget(QWidget):
    def __init__(self, parent= None):
        super(Widget, self).__init__(parent)
        layout = QGridLayout()

        self.setLayout(layout)

        btn = QPushButton('Push')
        layout.addWidget(btn, 0, 0)

        le = QLineEdit()
        layout.addWidget(le, 0, 1)


    def someFunc(self):
        print () ## should print texts entered in le 


app = QApplication(sys.argv)
widget = Widget()
widget.show()
app.exec_()

正如您在上面看到的,我希望“someFunc”方法通过单击“Push”按钮来打印放入文件中的任何文本。

如果有人知道如何解决这个问题,请告诉我谢谢!

【问题讨论】:

    标签: python pyqt4 qtextedit qlineedit


    【解决方案1】:

    您需要将按钮的clicked 信号连接到someFunc,并将le 设置为主窗口的属性(以便稍后访问)。

    因此,您的 Widget 类应如下所示:

    class Widget(QWidget):
        def __init__(self, parent= None):
            super(Widget, self).__init__(parent)
            layout = QGridLayout()
    
            self.setLayout(layout)
    
            btn = QPushButton('Push')
            # connect the signal to the slot
            btn.clicked.connect(self.someFunc)
            layout.addWidget(btn, 0, 0)
    
            # set an attribute
            self.le = QLineEdit()
            self.le.textChanged.connect(self.otherFunc)
            layout.addWidget(self.le, 0, 1)
    
        def someFunc(self):
            # use the attribute to get the text
            print('button-clicked:', self.le.text())
    
        def otherFunc(self, text):
            print('text-changed:', text)
    

    【讨论】:

    • 所以如果我在“self.le”中输入一些内容,它会自动发出输入一些文本的信号?
    • @ryan9025。为了那个原因。你需要使用类似textEdited 信号的东西。我在示例中添加了一些额外的代码来展示如何做到这一点。我建议你尝试一些the other signals 看看他们做了什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 1970-01-01
    • 1970-01-01
    • 2015-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多