def setupUi(self, Form): Form.setObjectName(_fromUtf8("QRangeSlider")) Form.resize(300, 30) Form.setStyleSheet(_fromUtf8(DEFAULT_CSS)) self.gridLayout = QtGui.QGridLayout(Form) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.gridLayout.setSpacing(0) self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self._splitter = QtGui.QSplitter(Form) self._splitter.setMinimumSize(QtCore.QSize(0, 0)) self._splitter.setMaximumSize(QtCore.QSize(16777215, 16777215)) self._splitter.setOrientation(QtCore.Qt.Horizontal) self._splitter.setObjectName(_fromUtf8("splitter")) self._head = QtGui.QGroupBox(self._splitter) self._head.setTitle(_fromUtf8("")) self._head.setObjectName(_fromUtf8("Head")) self._handle = QtGui.QGroupBox(self._splitter) self._handle.setTitle(_fromUtf8("")) self._handle.setObjectName(_fromUtf8("Span")) self._tail = QtGui.QGroupBox(self._splitter) self._tail.setTitle(_fromUtf8("")) self._tail.setObjectName(_fromUtf8("Tail")) self.gridLayout.addWidget(self._splitter, 0, 0, 1, 1) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form)
class DeletableLineEdit(QtGui.QWidget): """ Close button + line editor, used for modifiable key labels """ userModification = QtCore.Signal() buttonPressed = QtCore.Signal() def __init__(self, text=None, parent=None): super(DeletableLineEdit, self).__init__(parent) layout = QtGui.QHBoxLayout() self.setLayout(layout) delete_button = QtGui.QToolButton() layout.addWidget(delete_button) # Set the tool icons icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/soma_widgets_icons/delete")), QtGui.QIcon.Normal, QtGui.QIcon.Off) delete_button.setIcon(icon) self.line_edit = TimeredQLineEdit(text) layout.addWidget(self.line_edit) self.line_edit.userModification.connect(self.userModification) delete_button.pressed.connect(self.buttonPressed) def text(self): return self.line_edit.text() def setText(self, text): self.line_edit.setText(text)
def __init__(self, qLineEdit, timerInterval=None): ''' Parameters ---------- qLineEdit: (QtGui.QLineEdit instance) widget associated with this QLineEditModificationTimer. timerInterval: (milliseconds) minimum inactivity period before emitting userModification signal. Default value is QLineEditModificationTimer.defaultTimerInterval see: TimeredQLineEdit ''' QtCore.QObject.__init__(self) # QLineEdit<qt.QLineEdit> instance associated with this # QLineEditModificationTimer self.qLineEdit = weakref.proxy(qLineEdit) if timerInterval is None: self.timerInterval = self.defaultTimerInterval else: # minimum inactivity period before emitting C{userModification} # signal. self.timerInterval = timerInterval self.__timer = QtCore.QTimer(self) self.__timer.setSingleShot(True) self.__internalModification = False self.qLineEdit.textChanged.connect(self._userModification) # self.qLineEdit.lostFocus.connect(self._noMoreUserModification) self.qLineEdit.editingFinished.connect(self._noMoreUserModification) self.__timer.timeout.connect(self.modificationTimeout)
def onHelpClicked(self): """ Event to display the documentation of the active pipeline. """ # Create a dialog box to display the html documentation win = QtGui.QDialog() win.setWindowTitle("Pipeline Help") # Build the pipeline documentation location # Possible since common tools generate the sphinx documentation if self.pipeline: # Generate the url to the active pipeline documentation path_to_active_pipeline_doc = os.path.join( self.path_to_pipeline_doc[self.pipeline.id], "generated", self.pipeline.id.split(".")[1], "pipeline", self.pipeline.id + ".html") # Create and fill a QWebView help = QtWebKit.QWebView() help.load(QtCore.QUrl(path_to_active_pipeline_doc)) help.show() # Create and set a layout with the web view layout = QtGui.QHBoxLayout() layout.addWidget(help) win.setLayout(layout) # Display the window win.exec_() # No Pipeline loaded, cant't show the documentation message # Display a message box else: QtGui.QMessageBox.information(self.ui, "Information", "First load a pipeline!")
class TimeredQLineEdit(Qt.QLineEdit): ''' Create a QLineEdit instance that has an private attribute containing a QLineEditModificationTimer associated to self. Whenever the internal QLineEditModificationTimer emits a userModification signal, this signal is also emited by the TimeredQLineEdit instance. ''' userModification = QtCore.Signal() def __init__(self, *args, **kwargs): ''' All non keyword parameters of the constructor are passed to L{QLineEdit<QtGui.QLineEdit>} constructor. An optional C{timerInterval} keyword parameter can be given, it is passed to L{QLineEditModificationTimer} constructor. At the time this class was created, L{QLineEdit<qt.QLineEdit>} constructor did not accept keyword parameters. ''' timerInterval = kwargs.pop('timerInterval', None) if kwargs: Qt.QLineEdit.__init__(self, *args, **kwargs) else: Qt.QLineEdit.__init__(self, *args) self.__timer = QLineEditModificationTimer(self, timerInterval=timerInterval) self.__timer.userModification.connect(self.userModification) def stopInternalModification(self): ''' @see: L{QLineEditModificationTimer.stopInternalModification} ''' self.__timer.stopInternalModification() def startInternalModification(self): ''' @see: L{QLineEditModificationTimer.startInternalModification} ''' self.__timer.startInternalModification() def close(self): self.__timer.close() super(TimeredQLineEdit, self).close()
class QLineEditModificationTimer(QtCore.QObject): ''' A QLineEditModificationTimer instance is accociated to a QtGui.QLineEdit instance, it listens all user modification (Qt signal 'textChanged( const QString & )') and emits a signal 'userModification()' when timerInterval milliseconds passed since the last user modification. ''' # Default timer interval in milliseconds defaultTimerInterval = 2000 userModification = QtCore.Signal() def __init__(self, qLineEdit, timerInterval=None): ''' Parameters ---------- qLineEdit: (QtGui.QLineEdit instance) widget associated with this QLineEditModificationTimer. timerInterval: (milliseconds) minimum inactivity period before emitting userModification signal. Default value is QLineEditModificationTimer.defaultTimerInterval see: TimeredQLineEdit ''' QtCore.QObject.__init__(self) # QLineEdit<qt.QLineEdit> instance associated with this # QLineEditModificationTimer self.qLineEdit = weakref.proxy(qLineEdit) if timerInterval is None: self.timerInterval = self.defaultTimerInterval else: # minimum inactivity period before emitting C{userModification} # signal. self.timerInterval = timerInterval self.__timer = QtCore.QTimer(self) self.__timer.setSingleShot(True) self.__internalModification = False self.qLineEdit.textChanged.connect(self._userModification) # self.qLineEdit.lostFocus.connect(self._noMoreUserModification) self.qLineEdit.editingFinished.connect(self._noMoreUserModification) self.__timer.timeout.connect(self.modificationTimeout) def close(self): self.stop() self.qLineEdit.textChanged.disconnect(self._userModification) # self.qLineEdit.lostFocus.disconnect(self._noMoreUserModification) self.qLineEdit.editingFinished.disconnect(self._noMoreUserModification) self.__timer.timeout.disconnect(self.modificationTimeout) def _userModification(self, value): if not self.__internalModification: self.__timer.start(self.timerInterval) def modificationTimeout(self): self.userModification.emit() # self.qLineEdit.text()) def _noMoreUserModification(self): if self.__timer.isActive(): self.__timer.stop() self.userModification.emit() # self.qLineEdit.text()) def stopInternalModification(self): ''' Stop emitting C{userModification} signal when associated L{QLineEdit<qt.QLineEdit>} is modified. @see: L{startInternalModification} ''' self.__internalModification = False def startInternalModification(self): ''' Restart emitting C{userModification} signal when associated L{QLineEdit<qt.QLineEdit>} is modified. @see: L{stopInternalModification} ''' self.__internalModification = True def stop(self): ''' Stop the timer if it is active. ''' self.__timer.stop() def isActive(self): ''' Returns True if the timer is active, or False otherwise. ''' return self.__timer.isActive()
class QRangeSlider(QtGui.QWidget, Ui_Form): """ The QRangeSlider class implements a horizontal range slider widget. Inherits QWidget. Methods * __init__ (self, QWidget parent = None) * bool drawValues (self) * int end (self) * (int, int) getRange (self) * int max (self) * int min (self) * int start (self) * setBackgroundStyle (self, QString styleSheet) * setDrawValues (self, bool draw) * setEnd (self, int end) * setStart (self, int start) * setRange (self, int start, int end) * setSpanStyle (self, QString styleSheet) Signals * endValueChanged (int) * maxValueChanged (int) * minValueChanged (int) * startValueChanged (int) * rangeChanged (int, int) Customizing QRangeSlider You can style the range slider as below: :: QRangeSlider * { border: 0px; padding: 0px; } QRangeSlider #Head { background: #222; } QRangeSlider #Span { background: #393; } QRangeSlider #Span:active { background: #282; } QRangeSlider #Tail { background: #222; } Styling the range slider handles follows QSplitter options: :: QRangeSlider > QSplitter::handle { background: #393; } QRangeSlider > QSplitter::handle:vertical { height: 4px; } QRangeSlider > QSplitter::handle:pressed { background: #ca5; } """ # define splitter indices _SPLIT_START = 1 _SPLIT_END = 2 startValueChanged = QtCore.Signal(int) endValueChanged = QtCore.Signal(int) maxValueChanged = QtCore.Signal(int) minValueChanged = QtCore.Signal(int) startValueChanged = QtCore.Signal(int) rangeChanged = QtCore.Signal(int, int) def __init__(self, parent=None): """ Create a new QRangeSlider instance. :param parent: QWidget parent :return: New QRangeSlider instance. """ QtGui.QWidget.__init__(self, parent) self.setupUi(self) self.setMouseTracking(False) self._splitter.splitterMoved.connect(self._handleMoveSplitter) # head layout self._head_layout = QtGui.QHBoxLayout() self._head_layout.setSpacing(0) self._head_layout.setContentsMargins(0, 0, 0, 0) self._head.setLayout(self._head_layout) self.head = Head(self._head, main=self) self._head_layout.addWidget(self.head) # handle layout self._handle_layout = QtGui.QHBoxLayout() self._handle_layout.setSpacing(0) self._handle_layout.setContentsMargins(0, 0, 0, 0) self._handle.setLayout(self._handle_layout) self.handle = Handle(self._handle, main=self) self.handle.setTextColor((150, 255, 150)) self._handle_layout.addWidget(self.handle) # tail layout self._tail_layout = QtGui.QHBoxLayout() self._tail_layout.setSpacing(0) self._tail_layout.setContentsMargins(0, 0, 0, 0) self._tail.setLayout(self._tail_layout) self.tail = Tail(self._tail, main=self) self._tail_layout.addWidget(self.tail) # defaults self.setMin(0) self.setMax(99) self.setStart(0) self.setEnd(99) self.setDrawValues(True) self._movingHandle = False def min(self): """:return: minimum value""" return getattr(self, '__min', None) def max(self): """:return: maximum value""" return getattr(self, '__max', None) def setMin(self, value): """sets minimum value""" assert type(value) is int setattr(self, '__min', value) self.minValueChanged.emit(value) def setMax(self, value): """sets maximum value""" assert type(value) is int setattr(self, '__max', value) self.maxValueChanged.emit(value) def start(self): """:return: range slider start value""" return getattr(self, '__start', None) def end(self): """:return: range slider end value""" return getattr(self, '__end', None) def _setStart(self, value): """stores the start value only""" setattr(self, '__start', value) self.startValueChanged.emit(value) def setStart(self, value): """sets the range slider start value""" assert type(value) is int v = self._valueToPos(value) self._splitter.moveSplitter(v, self._SPLIT_START) self._setStart(value) def _setEnd(self, value): """stores the end value only""" setattr(self, '__end', value) self.endValueChanged.emit(value) def setEnd(self, value): """set the range slider end value""" assert type(value) is int v = self._valueToPos(value) self._splitter.moveSplitter(v, self._SPLIT_END) self._setEnd(value) def drawValues(self): """:return: True if slider values will be drawn""" return getattr(self, '__drawValues', None) def setDrawValues(self, draw): """sets draw values boolean to draw slider values""" assert type(draw) is bool setattr(self, '__drawValues', draw) def getRange(self): """:return: the start and end values as a tuple""" return (self.start(), self.end()) def setRange(self, start, end): """set the start and end values""" self.setStart(start) self.setEnd(end) self.rangeChanged.emit(start, end) def keyPressEvent(self, event): """overrides key press event to move range left and right""" key = event.key() if key == QtCore.Qt.Key_Left: s = self.start() - 1 e = self.end() - 1 elif key == QtCore.Qt.Key_Right: s = self.start() + 1 e = self.end() + 1 else: event.ignore() return event.accept() if s >= self.min() and e <= self.max(): self.setRange(s, e) def setBackgroundStyle(self, style): """sets background style""" self._tail.setStyleSheet(style) self._head.setStyleSheet(style) def setSpanStyle(self, style): """sets range span handle style""" self._handle.setStyleSheet(style) def _valueToPos(self, value): """converts slider value to local pixel x coord""" return int(self.width() * (float(value) / self.max())) def _posToValue(self, xpos): """converts local pixel x coord to slider value""" return int( ((xpos + self._splitter.handleWidth()) / float(self.width())) * self.max()) def _handleMoveSplitter(self, xpos, index): """private method for handling moving splitter handles""" hw = self._splitter.handleWidth() def _lockWidth(widget): width = widget.size().width() widget.setMinimumWidth(width) widget.setMaximumWidth(width) def _unlockWidth(widget): widget.setMinimumWidth(0) widget.setMaximumWidth(16777215) v = self._posToValue(xpos) if index == self._SPLIT_START: _lockWidth(self._tail) if v >= self.end(): return offset = -20 w = xpos + offset self._setStart(v) elif index == self._SPLIT_END: _lockWidth(self._head) if v <= self.start(): return offset = -40 w = self.width() - xpos + offset self._setEnd(v) _unlockWidth(self._tail) _unlockWidth(self._head) _unlockWidth(self._handle)
def preferences(self): '''Preferences for the dataviewer ''' #Get initial config: im_sec = Config().getViewerFramerate() config = Config().getViewerConfig() ref = Config().get_referential() dialog = Qt.QDialog() dialog.setWindowTitle('Preferences') dialog.resize(600, 400) layout = Qt.QVBoxLayout() layout.setContentsMargins(25, 25, 25, 25) dialog.setLayout(layout) #Change Neuro/Radio configuration config_layout = QHBoxLayout() title_config = Qt.QLabel() title_config.setText('Configuration: ') box = Qt.QComboBox() box.addItem('Neuro') box.addItem('Radio') config_layout.addWidget(title_config) config_layout.addWidget(box) if config == 'radio': box.setCurrentIndex(1) #set automatic time frame rate frame_rate_layout = QHBoxLayout() title = Qt.QLabel() title.setText('Automatic time image display:') slider = Qt.QSlider(Qt.Qt.Horizontal) slider.setRange(1, 100) slider.setValue(int(im_sec)) size = QtCore.QSize(180, 15) slider.setMinimumSize(size) slow_label = Qt.QLabel() fast_label = Qt.QLabel() slow_label.setText('slow') fast_label.setText('fast') frame_rate_layout.addWidget(title) frame_rate_layout.addWidget(slow_label) frame_rate_layout.addWidget(slider) frame_rate_layout.addWidget(fast_label) frame_rate_layout.insertSpacing(1, 200) #Change referential ref_layout = QHBoxLayout() title_ref = Qt.QLabel() title_ref.setText('Referential: ') box2 = Qt.QComboBox() box2.addItem('World Coordinates') box2.addItem('Image referential') ref_layout.addWidget(title_ref) ref_layout.addWidget(box2) box2.setCurrentIndex(int(ref)) #Set general vertical layout layout.addLayout(config_layout) layout.addLayout(frame_rate_layout) layout.addLayout(ref_layout) layout.addStretch(1) #Save and cancel buttons hlay = Qt.QHBoxLayout() layout.addLayout(hlay) ok = Qt.QPushButton('Save') hlay.addStretch(1) hlay.addWidget(ok) ok.clicked.connect(dialog.accept) ok.setDefault(True) cancel = Qt.QPushButton('Cancel') hlay.addWidget(cancel) cancel.clicked.connect(dialog.reject) hlay.addStretch(1) res = dialog.exec_() if res == Qt.QDialog.Accepted: new_config = box.currentText().lower() new_ref = box2.currentIndex() #Save Config parameters and reload images #when config and referential have changed Config().setViewerFramerate(slider.value()) Config().setViewerConfig(new_config) Config().set_referential(new_ref) if new_config != config: self.anaviewer.changeConfig(new_config) if new_ref != ref: self.anaviewer.changeRef()
fullTexture = np.dot(spi2gii, invsolmat) self.texture2[0].assign(fullTexture) self.TextObj.setTexture(self.texture2, True) self.TextObj.notifyObservers() self.app.processEvents() #mapping avec les leds currentIndex += 1 pdb.set_trace() def main(noapp=0): app = None if noapp == 0: print "NO APP" app = QtGui.QApplication(sys.argv) axon.initializeProcesses() ll = LocateLeds(app=app) ll.show() if noapp == 0: sys.exit(app.exec_()) if __name__ == "__main__": QtCore.pyqtRemoveInputHook() main()
def __init__(self, extra_options=None): """ Method to initialize the Application class. The capsulview application can be executed with command line options (that can also be passed to the class constructor as extra_options). From the command line, we can set the debug level with the -d option: * debug * info * warning * error * critical For exemple: >>> capsulview -d debug The default mode is error. From the command line we can also redirect all messages to a graphical message box with the -r option: >>> capsulview -r Parameters ---------- extra_options: list (optional) some additional options that are not passed through the command line. """ # Inheritance QtGui.QApplication.__init__(self, []) # Extra application options extra_options = extra_options or [] # Define a mapping to the logging level levels = { "debug": logging.DEBUG, "info": logging.INFO, "warning": logging.WARNING, "error": logging.ERROR, "critical": logging.CRITICAL } # Parse command line and internal options parser = optparse.OptionParser() parser.add_option("-d", "--debug", dest="debug", help="Set the logging level " "(debug, info, warning, error, or critical", metavar="LEVEL") parser.add_option("-r", "--redirect-to-messagebox", dest="redirect", action="store_true", default=False, help="Redirect all messages to the console") parser.add_option("-t", "--test", dest="test", action="store_true", default=False, help="Add a set of test pipelines") for args, kwargs in extra_options: parser.add_option(*args, **kwargs) self.options, self.arguments = parser.parse_args() # Logging format logging_format = ("[%(asctime)s] " "{%(pathname)s:%(lineno)d} " "%(levelname)s - %(message)s") date_format = "%Y-%m-%d %H:%M:%S" # If someone tried to log something before basicConfig is called, # Python creates a default handler that goes to the console and # will ignore further basicConfig calls: we need to remove the # handlers if there is one. while len(logging.root.handlers) > 0: logging.root.removeHandler(logging.root.handlers[-1]) # If the logging level is specified if self.options.debug is not None: # Get the real logging level from the mapping level = levels.get(self.options.debug, None) # If a no valid logging level is found raise an Exception if level is None: raise Exception("Warning : unknown logging level " "{0}".format(self.options.debug)) # Configure the logging module logging.basicConfig(level=level, format=logging_format, datefmt=date_format) # Disable deprecation warnings if we are not in the debug mode if level != logging.DEBUG: warnings.simplefilter("ignore", DeprecationWarning) # Set the default logging level else: logging.basicConfig(level=logging.ERROR, format=logging_format, datefmt=date_format) # Disable deprecation warnings warnings.simplefilter("ignore", DeprecationWarning) # Check if the redirection option is found: redirecect stdout and # stderr to a message box if self.options.redirect: # Create a message box self.message_box = QtGui.QTextEdit() # Redirect stdout and stderr sys.stdout = EmittingStream() sys.stderr = EmittingStream() # Connect with text written signal self.connect(sys.stdout, QtCore.SIGNAL('textWritten(QString)'), self._on_text_print) self.connect(sys.stderr, QtCore.SIGNAL('textWritten(QString)'), self._on_text_print) # Update root logger handler root_logger = logging.getLogger() h = root_logger.handlers[0] h.stream = sys.stdout