简体   繁体   English

QTermWidget:模拟按键Python / C ++

[英]QTermWidget: simulating a key press Python/C++

So I'm trying to send a simulated return key to QTermWidget in my program. 因此,我尝试将模拟的返回键发送到程序中的QTermWidget。 I have working version of this in both Python /Qt4 and C++/Qt4. 我在Python / Qt4和C ++ / Qt4中都有此版本。 At this point I really do not care if it is written in either language now that I have a decent grasp on C++ syntax. 由于我对C ++语法有很好的了解,因此我现在真的不在乎它是否用任何一种语言编写。 That being said an answer for either language would be a godsend. 话虽这么说,这两种语言的答案都是天赐之物。

So far I've tried 到目前为止,我已经尝试过

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

and

    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)

and a few other that I can't fully remember now. 还有其他一些我现在已经不记得了。

Thank you for any help. 感谢您的任何帮助。

Did you try this in C++? 您是否在C ++中尝试过?

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

This works for me, should be working with other widgets, too. 这对我有用,也应该与其他小部件一起使用。

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_())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM