簡體   English   中英

PyQt4:在QLineEdit / QTextEdit中讀取文本,並通過單擊按鈕將文本更改實現為某些功能

[英]PyQt4: Read texts in QLineEdit/QTextEdit and implement the text change into some functions by clicking a button

我想通過在窗口小部件中輸入一些文本來更改函數中的某些值。 我不確定應該使用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”方法通過單擊“推”按鈕來打印文件中放置的任何文本。

如果有人知道如何解決這個問題,請讓我知道謝謝!!

您需要將按鈕的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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM