在PyQt4中显示textEdit中的os.system()的输出,可以通过以下步骤实现:
- 导入必要的模块:import sys
from PyQt4 import QtGui
from PyQt4.QtCore import Qt, QProcess
- 创建一个自定义的TextEdit类,继承自QtGui.QTextEdit,并重写其keyPressEvent方法:class CustomTextEdit(QtGui.QTextEdit):
def __init__(self, parent=None):
super(CustomTextEdit, self).__init__(parent)
def keyPressEvent(self, event):
if event.key() == Qt.Key_Return:
command = self.toPlainText()
self.execute_command(command)
else:
super(CustomTextEdit, self).keyPressEvent(event)
def execute_command(self, command):
process = QProcess()
process.start('cmd', ['/c', command])
process.waitForFinished(-1)
output = process.readAllStandardOutput().data().decode('utf-8')
self.append(output)
- 创建一个主窗口类,继承自QtGui.QMainWindow,并在其构造函数中添加一个CustomTextEdit实例作为中心部件:class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setWindowTitle('Command Output')
text_edit = CustomTextEdit(self)
self.setCentralWidget(text_edit)
- 创建应用程序实例,并运行主循环:if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
这样,当在textEdit中输入命令并按下回车键时,程序将执行该命令并将输出显示在textEdit中。
注意:由于os.system()在PyQt中会导致程序阻塞,因此这里使用了QProcess来执行命令,并通过重定向标准输出来获取命令的输出结果。