lineedit中的pyqt按键事件

问题描述 投票:0回答:1

我创建了一个无标题的用户界面,其中存在一个行编辑。 现在我想立即获取我在 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_())

这是我导入的 untitled.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_())
python-3.x events pyqt signals-slots qlineedit
1个回答
6
投票

如果您想在输入行编辑时获取整个文本,您可以使用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)
© www.soinside.com 2019 - 2024. All rights reserved.