模仿QLineEdit上的returnPressed信号

时间:2019-05-07 00:55:18

标签: python pyqt pyqt4

我有一个QLineEdit小部件,您可以在其中以编程方式或通过用户输入来编辑文本。

虽然我设法使用户输入法正常工作,但是在使用tabRectsetText仍然有效的编程方式上却遇到了问题。

QLineEdit / tabRect发生在QTabBar的选项卡重命名之上。

def _renameTab(self, index, new_name=""):
    self._edited_tab_index = index
    if self._edited_tab_index != self.currentIndex():
        self.setCurrentIndex(self._edited_tab_index)

    rect = self.tabRect(index)
    top_margin = 3
    left_margin = 6
    self._rename_line_edit = QtGui.QLineEdit(self)
    self._rename_line_edit.show()
    self._rename_line_edit.move(
        rect.left() + left_margin, rect.top() + top_margin
    )
    self._rename_line_edit.resize(
        rect.width() - 2 * left_margin, rect.height() - 2 * top_margin
    )

    if new_name:
        self._rename_line_edit.setText(new_name)
        # self._rename_line_edit.clearFocus()
        # self._rename_line_edit.textEdited.connect(self._renameTabFinished)

    else:
        self._rename_line_edit.setText(self.tabText(index))

    self._rename_line_edit.selectAll()
    self._rename_line_edit.setFocus()
    self._rename_line_edit.editingFinished.connect(self._renameTabFinished)
    self.currentChanged.connect(self._renameTabFinished)

尝试使用clearFocus似乎没有帮助。

是否有一种类似于returnPressedtoggle()的QLineEdit模仿trigger()的方法?

1 个答案:

答案 0 :(得分:1)

您可以使用QCoreApplication :: postEvent()发送QKeyEvent:

from PyQt4 import QtCore, QtGui
from functools import partial
import random


class LineEdit(QtGui.QLineEdit):
    def emulate_returnPressed(self):
        keyEvent = QtGui.QKeyEvent(
            QtCore.QEvent.KeyPress, QtCore.Qt.Key_Return, QtCore.Qt.NoModifier
        )
        QtCore.QCoreApplication.postEvent(self, keyEvent)


class Widget(QtGui.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        lay = QtGui.QVBoxLayout(self)
        self.les = []
        for i in range(4):
            le = LineEdit("message-{}".format(i))
            le.returnPressed.connect(self.on_returnPressed)
            lay.addWidget(le)
            self.les.append(le)

        wrapper = partial(self.on_timeout, self.les)
        timer = QtCore.QTimer(self, timeout=wrapper, interval=1000)
        timer.start()

    def on_returnPressed(self):
        print("on_returnPressed", self.sender().text())

    def on_timeout(self, les):
        le = random.choice(self.les)
        le.emulate_returnPressed()


if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())