def __init__(self, parent, target, feat): super().__init__(parent) self._feat = feat layout = QtGui.QHBoxLayout(self) if feat.keys: wid = QtGui.QComboBox() if isinstance(feat.keys, dict): self._keys = list(feat.keys.keys()) else: self._keys = list(feat.keys) wid.addItems([str(key) for key in self._keys]) wid.currentIndexChanged.connect(self._combobox_changed) else: wid = QtGui.QLineEdit() wid.textChanged.connect(self._lineedit_changed) layout.addWidget(wid) self._key_widget = wid wid = WidgetMixin.from_feat(feat) wid.bind_feat(feat) wid.feat_key = self._keys[0] wid.lantz_target = target layout.addWidget(wid) self._value_widget = wid
def __init__(self, parent, targets): super().__init__(parent) layout = QtGui.QHBoxLayout(self) tab_widget = QtGui.QTabWidget(self) tab_widget.setTabsClosable(False) for target in targets: widget = DriverTestWidget(parent, target) tab_widget.addTab(widget, target.name) layout.addWidget(tab_widget)
def setupUi(self): # This method is called after gui has been loaded (referenced in self.widget) # to customize gui building. In this case, we are adding a plot widget. self.pw = pg.PlotWidget() self.curve = self.pw.plot(pen='y') layout = QtGui.QVBoxLayout() layout.addWidget(self.pw) self.widget.plotParent.setLayout(layout) self.scannerUi = AmplitudeScannerUi() layout = QtGui.QHBoxLayout() layout.addWidget(self.scannerUi.widget) self.widget.scanner_widget.setLayout(layout)
def __init__(self, argspec, parent=None, window_title='Function arguments', doc=None): super().__init__(parent) vlayout = QtGui.QVBoxLayout(self) layout = QtGui.QFormLayout() widgets = [] defaults = argspec.defaults if argspec.defaults else () defaults = ('', ) * (len(argspec.args[1:]) - len(defaults)) + defaults self.arguments = {} for arg, default in zip(argspec.args[1:], defaults): wid = QtGui.QLineEdit(self) wid.setObjectName(arg) wid.setText(json.dumps(default)) self.arguments[arg] = default layout.addRow(arg, wid) widgets.append(wid) wid.textChanged.connect(self.on_widget_change(wid)) if doc and arg in doc: wid.setToolTip(doc[arg]) self.widgets = widgets buttonBox = QtGui.QDialogButtonBox() buttonBox.setOrientation(QtCore.Qt.Horizontal) buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Ok) buttonBox.setEnabled(True) buttonBox.accepted.connect(self.accept) vlayout.addLayout(layout) label = QtGui.QLabel() label.setText('Values are decoded from text using as JSON.') vlayout.addWidget(label) vlayout.addWidget(buttonBox) self.buttonBox = buttonBox self.valid = {wid.objectName(): True for wid in self.widgets} self.setWindowTitle(window_title)
def setValue(self, value): if value is MISSING: font = QtGui.QFont() font.setItalic(True) self.setFont(font) return self.setCurrentIndex(self.__values.index(value))
def _initialized(driver): delta = time.time() - timing[driver] row = drivers.index(driver) widget.setItem( row, 2, QtGui.QTableWidgetItem(initialized_msg + ' ({:.1f} sec)'.format(delta)))
def _createGUITable(self): table = QtGui.QTableWidget(0, 3) table.setHorizontalHeaderLabels(["Name", "Class", "Status"]) table.verticalHeader().setVisible(False) table.resize(250, 50) table.resizeColumnToContents(0) return table
def setupUi(self, parent): self.resize(275, 172) self.setWindowTitle('Convert units') self.layout = QtGui.QVBoxLayout(parent) self.layout.setSizeConstraint(QtGui.QLayout.SetFixedSize) align = (QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter) self.layout1 = QtGui.QHBoxLayout() self.label1 = QtGui.QLabel() self.label1.setMinimumSize(QtCore.QSize(100, 0)) self.label1.setText('Convert from:') self.label1.setAlignment(align) self.layout1.addWidget(self.label1) self.source_units = QtGui.QLineEdit() self.source_units.setReadOnly(True) self.layout1.addWidget(self.source_units) self.layout.addLayout(self.layout1) self.layout2 = QtGui.QHBoxLayout() self.label2 = QtGui.QLabel() self.label2.setMinimumSize(QtCore.QSize(100, 0)) self.label2.setText('to:') self.label2.setAlignment(align) self.layout2.addWidget(self.label2) self.destination_units = QtGui.QLineEdit() self.layout2.addWidget(self.destination_units) self.layout.addLayout(self.layout2) self.message = QtGui.QLabel() self.message.setText('') self.message.setAlignment(QtCore.Qt.AlignCenter) self.layout.addWidget(self.message) self.buttonBox = QtGui.QDialogButtonBox() self.buttonBox.setOrientation(QtCore.Qt.Horizontal) self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Ok) self.layout.addWidget(self.buttonBox) self.buttonBox.setEnabled(False) self.buttonBox.accepted.connect(self.accept) self.destination_units.textChanged.connect(self.check) self.setLayout(self.layout) self.destination_units.setFocus()
def setValue(self, value): if value is MISSING: font = QtGui.QFont() font.setItalic(True) self.setFont(font) return elif isinstance(value, Q_): super().display(value.to(self._units).magnitude) else: super().display(value)
def __init__(self, drivers=None, dependencies=None, parent=None): super(InitializeWindow, self).__init__(parent) factory = QtGui.QItemEditorFactory() QtGui.QItemEditorFactory.setDefaultFactory(factory) self.drivers = drivers self.dependencies = dependencies self.createGUI()
def createGUI(self): # Demonstrate the supported widgets. # Uncomment to try others. self.widget = self._createGUITable() #self.widget = self._createGUILine() #self.widget = self._createGUIText() button = QtGui.QPushButton() button.setText('Initialize') button.setEnabled(True) button.clicked.connect(self.initialize) layout = QtGui.QVBoxLayout() layout.addWidget(button) layout.addWidget(self.widget) self.setLayout(layout) self.setWindowTitle("Driver initialization")
def validate(value): try: if value: value = json.loads(value) else: value = None palette = QtGui.QPalette() palette.setColor(widget.backgroundRole(), QtGui.QColor('white')) widget.setPalette(palette) self.arguments[name] = value self.valid[name] = True except: palette = QtGui.QPalette() palette.setColor(widget.backgroundRole(), QtGui.QColor(255, 102, 102)) widget.setPalette(palette) self.valid[name] = False self.buttonBox.setEnabled(all(self.valid.values()))
def setValue(self, value): """Set widget value scaled by units. """ if value is MISSING: font = QtGui.QFont() font.setItalic(True) self.setFont(font) elif isinstance(value, Q_): super().setValue(value.to(self._units).magnitude) else: super().setValue(value)
def connect_backend(self): super().connect_backend() self.widget.start_stop.clicked.connect(self.on_start_stop_clicked) self.widget.mode.currentIndexChanged.connect(self.on_mode_changed) self.widget.iterations.valueChanged.connect(self.recalculate) self.widget.duration.valueChanged.connect(self.recalculate) self.widget.interval.valueChanged.connect(self.recalculate) self.widget.progress_bar.setValue(0) self._ok_palette = QtGui.QPalette(self.widget.progress_bar.palette()) self._overrun_palette = QtGui.QPalette( self.widget.progress_bar.palette()) self._overrun_palette.setColor(QtGui.QPalette.Highlight, QtGui.QColor(QtCore.Qt.red)) self.backend.iteration.connect(self.on_iteration) self.backend.loop_done.connect(self.on_loop_done) self.request_start.connect(self.backend.start) self.request_stop.connect(self.backend.stop)
def setupUi(self): import pyqtgraph as pg pg.setConfigOptions(antialias=True) # This method is called after gui has been loaded (referenced in self.widget) # to customize gui building. In this case, we are adding a plot widget. self.pw = pg.PlotWidget() self.curve = self.pw.plot(pen='y') layout = QtGui.QVBoxLayout() layout.addWidget(self.pw) self.widget.placeholder.setLayout(layout)
def __init__(self, parent, target, feat): super().__init__(parent) layout = QtGui.QHBoxLayout(self) self._label = QtGui.QLabel() self._label.setText(feat.name) self._label.setFixedWidth(120) self._label.setToolTip(_rst_to_html(feat.__doc__)) layout.addWidget(self._label) if isinstance(feat.feat, DictFeat): self._widget = DictFeatWidget(parent, target, feat) else: self._widget = WidgetMixin.from_feat(feat) self._widget.bind_feat(feat) self._widget.lantz_target = target layout.addWidget(self._widget) self._get = QtGui.QPushButton() self._get.setText('get') self._get.setEnabled(self._widget.readable) self._get.setFixedWidth(60) layout.addWidget(self._get) self._set = QtGui.QPushButton() self._set.setText('set') self._set.setEnabled(self._widget.writable) self._set.setFixedWidth(60) layout.addWidget(self._set) self._get.clicked.connect(self.on_get_clicked) self._set.clicked.connect(self.on_set_clicked) self._widget._update_on_change = self._widget.writable self.widgets = (self._label, self._widget, self._get, self._set)
from lantz.ui.widgets import connect_driver # Import lantz.ui register an import hook that will replace calls to Qt by PyQt4 or PySide ... # and here we just use Qt and will work with both bindings! from lantz.utils.qt import QtGui, QtCore # These imports are from your own project from lantz.drivers.examples.dummydrivers import DummyFunGen # And we reuse the code from the command line application. from scanfrequency import scan_frequency qapp = QtGui.QApplication(sys.argv) # Load the UI from the QtDesigner file. You can also use pyuic4 to generate a class. main = QtGui.loadUi("scanfrequency.ui") Hz = Q_(1, "Hz") sec = Q_(1, "sec") with DummyFunGen() as inst: # Connect the main panel widgets to the instruments Feats, # matching by name connect_driver(main, inst, prefix="fungen") # Obtain a reference to the widgets controlling the scan parameters start = main.findChild((QtGui.QWidget,), "start") stop = main.findChild((QtGui.QWidget,), "stop") step = main.findChild((QtGui.QWidget,), "step") wait = main.findChild((QtGui.QWidget,), "wait")
def initialize_and_report(widget, drivers, register_finalizer=True, initializing_msg='Initializing ...', initialized_msg='Initialized', concurrent=True, dependencies=None): """Initialize drivers while reporting the status in a QtWidget. :param widget: Qt Widget where the status information is going to be shown. :param drivers: iterable of drivers to initialize. :param register_finalizer: register driver.finalize method to be called at python exit. :param initializing_msg: message to be displayed while initializing. :param initialized_msg: message to be displayed after successful initialization. :param concurrent: indicates that drivers with satisfied dependencies should be initialized concurrently. :param dependencies: indicates which drivers depend on others to be initialized. each key is a driver name, and the corresponding value is an iterable with its dependencies. :return: the QThread doing the initialization. """ timing = {} thread = QtCore.QThread() helper = InitializerHelper(drivers, register_finalizer, concurrent, dependencies) helper.moveToThread(thread) thread.helper = helper if isinstance(widget, QtGui.QTableWidget): def _initializing(driver): timing[driver] = time.time() row = drivers.index(driver) widget.setItem(row, 2, QtGui.QTableWidgetItem(initializing_msg)) def _initialized(driver): delta = time.time() - timing[driver] row = drivers.index(driver) widget.setItem( row, 2, QtGui.QTableWidgetItem(initialized_msg + ' ({:.1f} sec)'.format(delta))) def _exception(driver, e): delta = time.time() - timing[driver] row = drivers.index(driver) widget.setItem( row, 2, QtGui.QTableWidgetItem('{} ({:.1f} sec)'.format(e, delta))) def _done(duration): widget.setItem( len(drivers), 2, QtGui.QTableWidgetItem('{:.1f} sec'.format(duration))) thread.quit() widget.clearContents() widget.setRowCount(len(drivers) + 1) for row, driver in enumerate(drivers): widget.setItem(row, 0, QtGui.QTableWidgetItem(driver.name)) widget.setItem(row, 1, QtGui.QTableWidgetItem(driver.__class__.__name__)) widget.setItem(row, 2, QtGui.QTableWidgetItem('')) widget.resizeColumnToContents(0) widget.horizontalHeader().setStretchLastSection(True) elif isinstance(widget, QtGui.QLineEdit): def _initializing(driver): timing[driver] = time.time() widget.setText('{} ({}) > {}'.format(driver.name, driver.__class__.__name__, initializing_msg)) def _initialized(driver): delta = time.time() - timing[driver] widget.setText('{} ({}) > {} ({:.1f} sec)'.format( driver.name, driver.__class__.__name__, initialized_msg, delta)) def _exception(driver, e): delta = time.time() - timing[driver] widget.setText('{} ({}) > {} ({:.1f} sec)'.format( driver.name, driver.__class__.__name__, e, delta)) def _done(duration): widget.setText('Initialized in {:.1f} sec'.format(duration)) thread.quit() widget.setReadOnly(True) elif isinstance(widget, QtGui.QTextEdit): def _initializing(driver): timing[driver] = time.time() widget.append('{} ({}) > {}'.format(driver.name, driver.__class__.__name__, initializing_msg)) def _initialized(driver): delta = time.time() - timing[driver] widget.append('{} ({}) > {} ({:.1f} sec)'.format( driver.name, driver.__class__.__name__, initialized_msg, delta)) def _exception(driver, e): delta = time.time() - timing[driver] widget.append('{} ({}) > {} ({:.1f} sec)'.format( driver.name, driver.__class__.__name__, e, delta)) def _done(duration): widget.append('Initialized in {:.1f} sec'.format(duration)) thread.quit() widget.setReadOnly(True) else: raise TypeError('Unknown widget type {}.'.format(type(widget))) thread.started.connect(helper.process) helper.initializing.connect(_initializing) helper.initialized.connect(_initialized) helper.exception.connect(_exception) helper.finished.connect(_done) thread.start() return thread
from lantz import Q_ # Import from lantz a function to connect drivers to UI from lantz.ui.widgets import connect_driver # Import lantz.ui register an import hook that will replace calls to Qt by PyQt4 or PySide ... # and here we just use Qt and will work with both bindings! from lantz.utils.qt import QtGui, QtCore # These imports are from your own project from lantz.drivers.examples import LantzSignalGeneratorTCP # And we reuse the code from the command line application. from scanfrequency import scan_frequency qapp = QtGui.QApplication(sys.argv) # Load the UI from the QtDesigner file. You can also use pyuic4 to generate a class. main = QtGui.loadUi('scanfrequency.ui') Hz = Q_(1, 'Hz') sec = Q_(1, 'sec') with LantzSignalGeneratorTCP('localhost', 5678) as inst: # Connect the main panel widgets to the instruments Feats, # matching by name connect_driver(main, inst, prefix='fungen') # Obtain a reference to the widgets controlling the scan parameters start = main.findChild((QtGui.QWidget, ), 'start')
def _initializing(driver): timing[driver] = time.time() row = drivers.index(driver) widget.setItem(row, 2, QtGui.QTableWidgetItem(initializing_msg))
def _createGUILine(self): text = QtGui.QLineEdit() return text
def _createGUIText(self): text = QtGui.QTextEdit() return text
def _exception(driver, e): delta = time.time() - timing[driver] row = drivers.index(driver) widget.setItem( row, 2, QtGui.QTableWidgetItem('{} ({:.1f} sec)'.format(e, delta)))
def _done(duration): widget.setItem( len(drivers), 2, QtGui.QTableWidgetItem('{:.1f} sec'.format(duration))) thread.quit()
def _createGUILine(self): text = QtGui.QLineEdit() return text def _createGUITable(self): table = QtGui.QTableWidget(0, 3) table.setHorizontalHeaderLabels(["Name", "Class", "Status"]) table.verticalHeader().setVisible(False) table.resize(250, 50) table.resizeColumnToContents(0) return table qapp = QtGui.QApplication(sys.argv) dependencies = {'slave': ('master', )} drivers = [ FunGen3210(name='master'), FunGen3210(name='slave'), FunGen3210(name='sync') ] window = InitializeWindow(drivers=drivers, dependencies=dependencies) window.show() if sys.platform.startswith('darwin'): window.raise_()
def on_set_clicked(self): font = QtGui.QFont() font.setItalic(False) self._widget.setFont(font) self._widget.value_to_feat()
def __init__(self, parent, target): super().__init__(parent) self._lantz_target = target layout = QtGui.QVBoxLayout(self) label = QtGui.QLabel() label.setText(str(target)) layout.addWidget(label) recall = QtGui.QPushButton() recall.setText('Refresh') recall.clicked.connect(lambda x: target.refresh()) update = QtGui.QPushButton() update.setText('Update') update.clicked.connect( lambda x: target.update(self.widgets_values_as_dict())) auto = QtGui.QCheckBox() auto.setText('Update on change') auto.setChecked(True) auto.stateChanged.connect(self.update_on_change) hlayout = QtGui.QHBoxLayout() hlayout.addWidget(recall) hlayout.addWidget(update) hlayout.addWidget(auto) layout.addLayout(hlayout) self.writable_widgets = [] self.widgets = [] # Feat for feat_name, feat in sorted(target.feats.items()): try: feat_widget = LabeledFeatWidget(self, target, feat) self.widgets.append(feat_widget) if feat_widget.writable: self.writable_widgets.append(feat_widget) layout.addWidget(feat_widget) except Exception as ex: logger.debug('Could not create control for {}: {}'.format( feat_name, ex)) if __PRINT_TRACEBACK__: import traceback traceback.print_exc() # Actions line = QtGui.QFrame(self) #self.line.setGeometry(QtCore.QRect(110, 80, 351, 31)) line.setFrameShape(QtGui.QFrame.HLine) line.setFrameShadow(QtGui.QFrame.Sunken) layout.addWidget(line) actions_label = QtGui.QLabel(self) actions_label.setText('Actions:') actions_label.setFixedWidth(120) self.actions_combo = QtGui.QComboBox(self) self.actions_combo.addItems(list(target.actions.keys())) actions_button = QtGui.QPushButton(self) actions_button.setFixedWidth(60) actions_button.setText('Run') actions_button.clicked.connect(self.on_run_clicked) alayout = QtGui.QHBoxLayout() alayout.addWidget(actions_label) alayout.addWidget(self.actions_combo) alayout.addWidget(actions_button) layout.addLayout(alayout)
try: from docutils import core as doc_core except ImportError: class doc_core(object): @staticmethod def publish_parts(rst, *args, **kwargs): return rst from .. import Q_, Driver, initialize_many from ..feat import MISSING, DictFeat from ..log import get_logger QtGui.QToolTip.setFont(QtGui.QFont('SansSerif', 10)) logger = get_logger('lantz.ui', False) def _rst_to_html(rst): """Convert rst docstring to HTML. """ parts = doc_core.publish_parts(rst, writer_name="html") return parts['body'] def _params_doc(rst): """Extract """ if not rst: