Skip to content

Instantly share code, notes, and snippets.

@kinverarity1
Last active August 29, 2015 14:01
Show Gist options
  • Save kinverarity1/9477879b943820ed6925 to your computer and use it in GitHub Desktop.
Save kinverarity1/9477879b943820ed6925 to your computer and use it in GitHub Desktop.
Wrappers for common Qt tasks.
import logging
import os
# Choose which library to use.
QT_LIBRARY = 'PySide'
if QT_LIBRARY == 'PySide':
from PySide import QtGui, QtCore
elif QT_LIBRARY == 'PyQt4':
from PyQt4 import QtGui, QtCore
else:
raise Exception('QT_LIBRARY must be either "PySide" or "PyQt4"')
Qt = QtCore.Qt
logger = logging.getLogger(__name__)
class ActionHandler(object):
'''A base class for Qt widgets, to make it easy to handle adding actions.
Intended to be inherited, not instantiated directly.
'''
def __init__(self):
self.actions = []
def create_action(self, text, slot=None, shortcut=None, icon=None,
tip=None, checkable=False, signal='triggered'):
'''Add an action.
Args:
- *icon*: filename
- *shortcut*: str e.g. <Ctrl-W>
- *slot*: function or method
- *tip*: string
- *checkable*: bool
- *signal*: attribute of the action
'''
action = QtGui.QAction(text, self)
if icon:
action.setIcon(QtGui.QIcon(":/%s.png" % icon))
if shortcut:
action.setShortcut(shortcut)
if tip:
action.setToolTip(tip)
action.setStatusTip(tip)
if checkable:
action.setCheckable(True)
if slot and signal:
getattr(action, signal).connect(slot)
return action
@staticmethod
def add_actions(self, target, actions):
'''Add actions to a target, like a ToolBar or Menu.
Args:
- *target*: should have an addSeparator() and addAction(action)
methods.
- *actions*: iterable sequence containing QActions
'''
for action in actions:
if action is None:
target.addSeparator()
else:
target.addAction(action)
def add_action_names(self, target, actions):
'''Add actions to a target, like a ToolBar or Menu.
Args:
- *target*: should have an addSeparator() and addAction(action)
methods.
- *actions*: strings referring to objects in self.actions (a dict)
'''
for action_name in actions:
if action_name:
action = getattr(self.actions, action_name)
else:
action = None
if action is None:
target.addSeparator()
else:
target.addAction(action)
class Widget(ActionHandler, QtGui.QWidget):
'''QWidget wrapper -- see :class:`ActionHandler`.
'''
def __init__(self, *args, **kwargs):
ActionHandler.__init__(self)
QtGui.QWidget.__init__(self, *args, **kwargs)
class MainWindow(ActionHandler, QtGui.QMainWindow):
'''QMainWindow wrapper -- see :class:`ActionHandler`.
'''
def __init__(self, app_name='Application', **kwargs):
self.app_name = app_name
ActionHandler.__init__(self)
QtGui.QMainWindow.__init__(self, **kwargs)
def init_settings(self):
try:
self.restore_settings()
except:
logger.warning('Failed to restore QSettings')
def restore_settings(self):
settings = QtCore.QSettings()
self.restoreGeometry(settings.value('geometry'))
self.restoreState(settings.value('windowState'))
self.area.restoreState(settings.value('dockState'))
def remember_settings(self):
settings = QtCore.QSettings()
settings.setValue('geometry', self.saveGeometry())
settings.setValue('windowState', self.saveState())
settings.setValue('dockState', self.area.saveState())
def closeEvent(self, event):
self.remember_settings()
QtGui.QMainWindow.closeEvent(self, event)
def set_title_message(self, message):
self.setWindowTitle('%s : %s' % (self.app_name, message))
class ExtendedCombo(QtGui.QComboBox):
'''Taken from http://stackoverflow.com/a/4829759/596328
'''
def __init__(self, parent=None):
super(ExtendedCombo, self).__init__(parent)
self.setFocusPolicy(Qt.StrongFocus)
self.setEditable(True)
self.completer = QtGui.QCompleter(self)
self.completer.setCompletionMode(QtGui.QCompleter.UnfilteredPopupCompletion)
self.pFilterModel = QtGui.QSortFilterProxyModel(self)
self.pFilterModel.setFilterCaseSensitivity(Qt.CaseInsensitive)
self.completer.setPopup(self.view())
self.setCompleter(self.completer)
self.lineEdit().textEdited[unicode].connect(self.pFilterModel.setFilterFixedString)
self.completer.activated.connect(self.setTextIfCompleterIsClicked)
def setModel(self, model):
super(ExtendedCombo, self).setModel(model)
self.pFilterModel.setSourceModel(model)
self.completer.setModel(self.pFilterModel)
def setModelColumn(self, column):
self.completer.setCompletionColumn(column)
self.pFilterModel.setFilterKeyColumn(column)
super(ExtendedCombo, self).setModelColumn(column)
def view(self):
return self.completer.popup()
def index(self):
return self.currentIndex()
def setTextIfCompleterIsClicked(self, text):
if text:
index = self.findText(text)
self.setCurrentIndex(index)
class OutLog(object):
def __init__(self, edit, out=None, color=None):
self.edit = edit
self.out = None
self.color = color
def write(self, m):
if self.color:
tc = self.edit.textColor()
self.edit.setTextColor(self.color)
self.edit.moveCursor(QtGui.QTextCursor.End)
self.edit.insertPlainText( m )
if self.color:
self.edit.setTextColor(tc)
if self.out:
self.out.write(m)
def open_file(parent, path=None):
if path is None:
path = os.getcwd()
dialog = QtGui.QFileDialog()
dialog.setFileMode(QtGui.QFileDialog.ExistingFile)
fmt_str = formats.get_qt_format_string()
fn = dialog.getOpenFileName(parent,
'Open file', path,
fmt_str)
fn1 = str(fn[0])
logger.info('QT open file dialog returning %s' % fn1)
return fn1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment