QTermWidget:模拟按键Python/C++

QTermWidget: simulating a key press Python/C++

本文关键字:Python C++ 模拟 QTermWidget      更新时间:2023-10-16

所以我试图在程序中向QTermWidget发送一个模拟的返回键。我在Python/Qt4和C++/Qt4中都有这方面的工作版本。在这一点上,我真的不在乎它是否用任何一种语言编写,因为我已经掌握了C++语法。话虽如此,任何一种语言的答案都是天赐之物。

到目前为止,我已经尝试过

   QTest.KeyClick(self.Terminal, Qt.KeyReturn, Qt.NoModifier) // syntax is python here

    key_press = QKeyEvent(QEvent.KeyPress, Qt.Key_Return, Qt.NoModifier)
    self.Terminal.keyPressEvent(key_press)
    key_release = QKeyEvent(QEvent.KeyRelease, Qt.Key_Return, Qt.NoModifier)
    self.Terminal.keyPressEvent(key_release)

还有一些我现在记不清了。

谢谢你的帮助。

你在C++中尝试过这个吗?

QKeyEvent *ev = new QKeyEvent( QEvent::KeyPress, Qt::Key_Return, Qt::NoModifier );
myApp->postEvent( receivingWidget, ev );

这对我有效,应该也能与其他小部件一起使用。

import sys
from PyQt4 import QtCore, QtGui, Qt
from ChildWindow import ChildWindow
class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        QtCore.QTimer.singleShot(500, self.showChildWindow)
        self.textEdit = QtGui.QTextEdit(self)
        self.textEdit.resize(100, 100)
    def showChildWindow(self):
        QtGui.QApplication.sendEvent(self.textEdit, QtGui.QKeyEvent(QtGui.QKeyEvent.KeyPress, QtCore.Qt.Key_A, QtCore.Qt.NoModifier, "hello"))
        QtGui.QApplication.sendEvent(self.textEdit, QtGui.QKeyEvent(QtGui.QKeyEvent.KeyPress, QtCore.Qt.Key_Return, QtCore.Qt.NoModifier))

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = MainWindow()
    myapp.show()
    sys.exit(app.exec_())