1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
|
#!/usr/bin/env python
"""
pythonconsolewidget.py
A Python console custom widget for Qt Designer.
Copyright (C) 2006 David Boddie <david@boddie.org.uk>
Copyright (C) 2005-2006 Trolltech ASA. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
from PyQt4 import QtCore, QtGui
class PythonConsoleWidget(QtGui.QLineEdit):
"""PythonConsoleWidget(QtGui.QLineEdit)
Provides a custom widget to accept Python expressions and emit output
to other components via a custom signal.
"""
pythonOutput = QtCore.pyqtSignal(str)
def __init__(self, parent=None):
super(PythonConsoleWidget, self).__init__(parent)
self.history = []
self.current = -1
self.returnPressed.connect(self.execute)
def keyReleaseEvent(self, event):
if event.type() == QtCore.QEvent.KeyRelease:
if event.key() == QtCore.Qt.Key_Up:
current = max(0, self.current - 1)
if 0 <= current < len(self.history):
self.setText(self.history[current])
self.current = current
event.accept()
elif event.key() == QtCore.Qt.Key_Down:
current = min(len(self.history), self.current + 1)
if 0 <= current < len(self.history):
self.setText(self.history[current])
else:
self.clear()
self.current = current
event.accept()
def execute(self):
# Define this here to give users something to look at.
qApp = QtGui.qApp
self.expression = self.text()
try:
result = str(eval(str(self.expression)))
# Emit the result of the evaluated expression.
self.pythonOutput.emit(result)
# Clear the line edit, append the successful expression to the
# history, and update the current command index.
self.clear()
self.history.append(self.expression)
self.current = len(self.history)
except:
pass
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
widget = PythonConsoleWidget()
widget.show()
sys.exit(app.exec_())
|