lineedit

时间:2017-09-30 18:23:27

标签: python-3.x pyqt pyqt4

我创建了一个无标题的ui,其中存在一个lineedit。 现在我想得到我在lineedit中输入的任何值的值 我发现它可以使用keypressevent完成,但我完全没有理解如何在lineedit中使用它

from untitled import *
from PyQt4 import QtGui # Import the PyQt4 module we'll need
import sys # We need sys so that we can pass argv to QApplication
import os

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


class MainWindow(QMainWindow, Ui_Dialog):
    def event(self, event):
        if type(event) == QtGui.QKeyEvent:
             print (event.key())

    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.setupUi(self)
        #here i want to get what is keypressed in my lineEdit 

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

这是我导入的无标题.py代码

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

# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName(_fromUtf8("Dialog"))
        Dialog.resize(662, 207)
        self.lineEdit = QtGui.QLineEdit(Dialog)
        self.lineEdit.setGeometry(QtCore.QRect(50, 30, 113, 27))
        self.lineEdit.setObjectName(_fromUtf8("lineEdit"))

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))


if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    Dialog = QtGui.QDialog()
    ui = Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.show()
    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:1)

如果您想在输入的行编辑中获取整个文本,则可以使用textEdited信号。但是,如果您只想获取按下的当前键,则可以使用event-filter

以下是如何使用这两种方法:

class MainWindow(QMainWindow, Ui_Dialog):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.lineEdit.installEventFilter(self)
        self.lineEdit.textEdited.connect(self.showCurrentText)

    def eventFilter(self, source, event):
        if (event.type() == QEvent.KeyPress and
            source is self.lineEdit):
            print('key press:', (event.key(), event.text()))
        return super(MainWindow, self).eventFilter(source, event)

    def showCurrentText(self, text):
        print('current-text:', text)