def __init__(self, parent = None): QtGui.QWidget.__init__(self, parent) loader = QUiLoader() file = QtCore.QFile("createRoom1.ui") file.open(QtCore.QFile.ReadOnly) widget = loader.load(file, parent) file.close()
def __init__(self): QApplication.__init__(self, sys.argv) loader = QUiLoader() self.window = loader.load("interface.ui") self.window.progressBar.hide() self.settings = Settings() self.math = Math(self.settings) try: self.plot = MatplotlibWidget() self.window.plot.addWidget(self.plot) except: pass self.settings.changed.connect(self.onSettingsChanged) try: self.device = Device() except IOError, e: print e QMessageBox.warning(self.window, "LaserExposer", "Device not connected") return
def testCase(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'test.ui') result = loader.load(filePath, w) self.assert_(isinstance(result.child_object, QtGui.QFrame))
def testCase(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'action.ui') result = loader.load(filePath, w) self.assert_(isinstance(result.actionFoo, QtGui.QAction))
def loadDialog(file_name): loader = QUiLoader() the_file = QFile(file_name) the_file.open(QFile.ReadOnly) ret_val = loader.load(the_file) the_file.close() return ret_val
def findOrSaveConfig(self): infile = QFile('ui/config_path.ui') infile.open(QFile.ReadOnly) loader = QUiLoader() dialog = loader.load(infile, self.window) infile.close() def browse(): path = QFileDialog.getSaveFileName(dialog, u"Choose or create a configuration file", dialog.pathBox.text())[0] if path != '': dialog.pathBox.setText(path) def cancel(): dialog.hide() def ok(): autodetectPort = dialog.autodetect.checkState() == Qt.Checked configPath = os.path.expanduser(dialog.pathBox.text()) dialog.hide() self.start(configPath, autodetectPort) dialog.show() dialog.pathBox.setText(os.path.expanduser('~/.config/tangelo/tangelo.conf')) dialog.browseButton.clicked.connect(browse) dialog.cancelButton.clicked.connect(cancel) dialog.okButton.clicked.connect(ok)
def __init__(self): loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'bug_426.ui') self.widget = loader.load(filePath) self.group = QtGui.QActionGroup(self.widget) self.widget.show() QtCore.QTimer.singleShot(0, self.widget.close)
def __init__(self): super(TreeviewWidgetSelectProve, self).__init__() ui_file_path = os.path.join( '/home/n130s/link/ROS/groovy_quantal/catkin_ws/src/rqt_prove', 'resource', 'treeview_2.ui') loader = QUiLoader(self) ui_file = QFile(ui_file_path) self._widget_top = loader.load(ui_file, self) self._std_model = QStandardItemModel() self._rootitem = self._std_model.invisibleRootItem() item_r_1 = QStandardItem("r1") self._rootitem.appendRow(item_r_1) # self._rootitem.appendRow(item_r_2) print('_rootitem index={}'.format(self._rootitem.index())) self._treeview = self._widget_top.findChild(QTreeView, '_treeview') self._treeview.setModel(self._std_model) self.selectionModel = self._widget_top._treeview.selectionModel() print('del/sel?\tde/sel index\tde/sel.row\tde/sel.dat\tparent\tinternal id') self._widget_top.show()
def __init__(self): # super(SimplyTimer, self).__init__() loader = QUiLoader() uiFile = QtCore.QFile('./timer.ui') uiFile.open(QtCore.QFile.ReadOnly) self._myWidget = loader.load(uiFile) uiFile.close() self._tryIcon = QtGui.QSystemTrayIcon(self._myWidget) icon = QtGui.QIcon(QtGui.QPixmap(':/Timer.png')) self._myWidget.setWindowIcon(icon) self._tryIcon.setIcon(icon) self._myWidget.uiStartButton.clicked.connect(self.start) self._myWidget.stopButton.clicked.connect(self.stop) self._tryIcon.activated.connect(self.onTryClicked) self.__timeEdit = self._myWidget.uiTimeEdit self._timer = QtCore.QTimer() self._timer.timeout.connect(self.timerHit) self._updateTimer = QtCore.QTimer() self._updateTimer.timeout.connect(self.update) self._tryIcon.show() self._myWidget.show()
def main(argv=None): if argv is None: argv = sys.argv app = QApplication(argv) engine = QScriptEngine() if HAS_DEBUGGER: debugger = QScriptEngineDebugger() debugger.attachTo(engine) debugWindow = debugger.standardWindow() debugWindow.resize(1024, 640) scriptFileName = './calculator.js' scriptFile = QFile(scriptFileName) scriptFile.open(QIODevice.ReadOnly) engine.evaluate(unicode(scriptFile.readAll()), scriptFileName) scriptFile.close() loader = QUiLoader() ui = loader.load(':/calculator.ui') ctor = engine.evaluate('Calculator') scriptUi = engine.newQObject(ui, QScriptEngine.ScriptOwnership) calc = ctor.construct([scriptUi]) if HAS_DEBUGGER: display = ui.findChild(QLineEdit, 'display') display.connect(display, SIGNAL('returnPressed()'), debugWindow, SLOT('show()')) ui.show() return app.exec_()
def loadCustomWidget(self,UIfile): loader = QUiLoader() file_ui = QtCore.QFile(UIfile) file_ui.open(QtCore.QFile.ReadOnly) self.mainWidget = loader.load(file_ui, self) self.setWindowTitle("Implicit Mapper") file_ui.close()
def getWidget(path, load): qLoader = QUiLoader() qFile = QtCore.QFile(path) qFile.open(QtCore.QFile.ReadOnly) ui = qLoader.load(qFile, load) qFile.close() return ui
def loadWindowFromFile(file_name): '''Load the window definition from the resource ui file''' loader = QUiLoader() ui_file = QFile(file_name) ui_file.open(QFile.ReadOnly) the_window = loader.load(ui_file) ui_file.close() return the_window
def testPythonCustomWidgets(self): w = QtGui.QWidget() loader = QUiLoader() loader.registerCustomWidget(MyWidget) filePath = os.path.join(os.path.dirname(__file__), 'pycustomwidget.ui') result = loader.load(filePath, w) self.assert_(isinstance(result.custom, MyWidget)) self.assert_(result.custom.isPython())
def __init__(self): QtGui.QWidget.__init__(self) loader = QUiLoader() widget = loader.load(adjust_filename('bug_552.ui', __file__), self) self.children = [] for child in widget.findChildren(QtCore.QObject, None): self.children.append(child) self.t = widget.tabWidget self.t.removeTab(0)
def __init__(self): loader = QUiLoader() self.__ui = loader.load(_UI_PATH) self.rfid_lock = False self.__ui.is_done.clicked.connect(self.__done) self.__ui.get_rfid.clicked.connect(self.__get_rfid) self.__ui.discard_photo.clicked.connect(self.__discard_photo) self.__ui.add_room.clicked.connect(self.__add_new_allowed_room) self.__ui.take_photo.clicked.connect(self.__take_photo)
def loadHyperlinkDialog(self): ''' Load dialog from ui file for defining hyperlink ''' loader = QUiLoader() ui_file = QFile(':/hyperlink.ui') # UI_DIALOG_FILE) ui_file.open(QFile.ReadOnly) self.hyperlink_dialog = loader.load(ui_file) ui_file.close() self.hyperlink_dialog.accepted.connect(self.hyperlinkChanged) self.hlink_field = self.hyperlink_dialog.findChild(QLineEdit, 'hlink')
def createWidget(self): # Override the existing widget # TODO: Do I need to delete anything explicitly? infile = QFile('ui/process_widget.ui') infile.open(QFile.ReadOnly) loader = QUiLoader() self.widget = loader.load(infile, Globals.mainWindow.window) infile.close() self.updateWidget(True)
def testBug909(self): fileName = QFile(adjust_filename('bug_909.ui', __file__)) loader = QUiLoader() main_win = loader.load(fileName) self.assertEqual(sys.getrefcount(main_win), 2) fileName.close() tw = QTabWidget(main_win) main_win.setCentralWidget(tw) main_win.show()
def __init__(self, parent=None): super(GUI, self).__init__(getMayaMainWindow()) loader = QUiLoader() uiFilePath = os.path.join(os.path.dirname(__file__), 'PoseLibrary.ui') self.UI = loader.load(uiFilePath) self.setCentralWidget(self.UI) self.setWindowTitle(Define.WINDOW_TITLE) self.setObjectName(Define.WINDOW_NAME) self.resize(Define.MAINWINDOWSIZEX, Define.MAINWINDOWSIZEY) self.__setui() self.__setSlots()
def main(argv=None): if argv is None: argv = sys.argv app = QApplication(argv) loader = QUiLoader() ui = loader.load('softvis.ui') print "s" ui.show() # engine = QScriptEngine() return app.exec_()
def _load_ui_pyside(path, parent): from PySide.QtUiTools import QUiLoader loader = QUiLoader() # must register custom widgets referenced in .ui files for w in _custom_widgets(): loader.registerCustomWidget(w) widget = loader.load(path, parent) return widget
class WouseSetupDialog(object): """A dialog box for setting session parameters for training the wouse.""" def __init__(self): """ Load .ui file from QtDesigner, add callbacks as necessary""" ui_file = WOUSE_PKG+'/src/wouse/wouse_train_options.ui' self.dialog = QUiLoader().load(ui_file) self.dialog.rounds_spin.valueChanged.connect(self.update_time) self.dialog.recording_spin.valueChanged.connect(self.update_time) self.dialog.recovery_spin.valueChanged.connect(self.update_time) self.dialog.file_button.clicked.connect(self.file_button_cb) self.dialog.file_field_edit.setText(WOUSE_PKG+'/data/') self.dialog.buttonBox.accepted.connect(self.ok_cb) self.dialog.buttonBox.rejected.connect(self.cancel_cb) self.update_time() def file_button_cb(self): """Use file dialog to get .csv file. Check for csv, update Lineedit""" direc = self.dialog.file_field_edit.text() filename = QFileDialog.getOpenFileName(self.dialog, caption="File to stop wouse training data", dir=direc, filter="*.csv") if len(filename[0]) != 0: if filename[0][-4:] != '.csv': QMessageBox.warning(self.dialog, "Warning: Invalid File", "Warning: Selected File does not appear to be a CSV (.csv)\ data file.") self.dialog.file_field_edit.setText(filename[0]) def calc_time(self): """Calculate the time (s) required for full run with current settings""" tot_time = (self.dialog.recording_spin.value()+ self.dialog.recovery_spin.value()) return len(ACTIONS)*self.dialog.rounds_spin.value()*tot_time def update_time(self): """Parse time to minutes:seconds format, update interface""" time = self.calc_time() mins = str(int(time)/60) secs = str(int(round(time%60.))) if len(secs)==1: secs = "".join(['0',secs]) self.dialog.duration.setText('%s:%s' %(mins,secs)) def ok_cb(self): """Check for acceptable file. Warn if bad, if good, close, return 1""" if self.dialog.file_field_edit.text()[-4:] != '.csv': return QMessageBox.warning(self.dialog, "Warning: Invalid File", "Please choose a valid CSV (.csv) data file.") self.dialog.accept() def cancel_cb(self): """ Close dialog, return 0/Rejected""" self.dialog.reject()
def testLoadFileUnicodeFilePath(self): filePath = str(os.path.join(os.path.dirname(__file__), 'test.ui')) loader = QUiLoader() parent = QWidget() w = loader.load(filePath, parent) self.assertNotEqual(w, None) self.assertEqual(len(parent.children()), 1) child = w.findChild(QWidget, "child_object") self.assertNotEqual(child, None) self.assertEqual(w.findChild(QWidget, "grandson_object"), child.findChild(QWidget, "grandson_object"))
def __init__(self): loader = QUiLoader() self.__ui = loader.load(_UI_PATH) self.show = self.__ui.show self.__ui.add.clicked.connect(self.__add_handler) self.__ui.remove.clicked.connect(self.__remove_handler) self.__ui.allowed_persons.itemDoubleClicked.connect(self.__person_double_clicked) self.__person_dao = PersonDAO() self.__cache = CacheCoeherenceManager() self.__refresh()
def __init__(self, parent=None): super(self.__class__, self).__init__(parent=parent) loader = QUiLoader() self.ui = loader.load('gotocelldialog.ui', self) mainLayout = QtGui.QVBoxLayout() mainLayout.addWidget(self.ui) self.setLayout(mainLayout) # 자식 위젯 취득하기 1 print self.ui.verticalLayout.objectName() # 자식 위젯 취득하기 2 (타입명, 오브젝트명) print self.ui.findChild(QtGui.QPushButton, 'cancelButton').objectName()
def findTangelo(): infile = QFile('ui/find_tangelo.ui') infile.open(QFile.ReadOnly) loader = QUiLoader() dialog = loader.load(infile, None) infile.close() if sys.platform.startswith('win'): Globals.pythonPath = subprocess.Popen(['where', 'python'], stdout=subprocess.PIPE).communicate()[0].strip() Globals.tangeloPath = subprocess.Popen(['where', 'tangelo'], stdout=subprocess.PIPE).communicate()[0].strip() else: Globals.pythonPath = subprocess.Popen(['which', 'python'], stdout=subprocess.PIPE).communicate()[0].strip() Globals.tangeloPath = subprocess.Popen(['which', 'tangelo'], stdout=subprocess.PIPE).communicate()[0].strip() if os.path.exists(Globals.pythonPath): dialog.pythonPathBox.setText(Globals.pythonPath) if os.path.exists(Globals.tangeloPath): dialog.tangeloPathBox.setText(Globals.tangeloPath) def pythonBrowse(): path = QFileDialog.getOpenFileName(dialog, u"Find python", dialog.pythonPathBox.text())[0] if path != '': dialog.pythonPathBox.setText(path) def tangeloBrowse(): path = QFileDialog.getOpenFileName(dialog, u"Find tangelo", dialog.tangeloPathBox.text())[0] if path != '': dialog.tangeloPathBox.setText(path) def cancel(): dialog.hide() sys.exit() def ok(): Globals.pythonPath = os.path.expanduser(dialog.pythonPathBox.text()) Globals.tangeloPath = os.path.expanduser(dialog.tangeloPathBox.text()) if not os.path.exists(Globals.pythonPath): Globals.criticalError("Sorry, that python interpreter doesn't exist.") return if not os.path.exists(Globals.tangeloPath): Globals.criticalError("Sorry, that tangelo executable doesn't exist.") return Globals.mainWindow = Overview() Globals.mainWindow.refresh() dialog.hide() dialog.show() dialog.tangeloBrowse.clicked.connect(tangeloBrowse) dialog.pythonBrowse.clicked.connect(pythonBrowse) dialog.cancelButton.clicked.connect(cancel) dialog.okButton.clicked.connect(ok)
def __init__(self, baseinstance): """ Create a loader for the given ``baseinstance``. The user interface is created in ``baseinstance``, which must be an instance of the top-level class in the user interface to load, or a subclass thereof. ``parent`` is the parent object of this loader. """ QUiLoader.__init__(self, baseinstance) self.baseinstance = baseinstance
def __init__(self): super(NoTuneAutoSweepGUI,self).__init__() loader = QUiLoader() UIfile = QtCore.QFile("NoTuneAutoSweepGUI.ui") UIfile.open(QtCore.QFile.ReadOnly) self.myWidget = loader.load(UIfile,self) UIfile.close() self.initUI() #***********************************************************# # Create New Thread # #***********************************************************# self.statsThread = UpdateStatsThread() self.statsThread.start(QtCore.QThread.TimeCriticalPriority)
def loadUi(path, parent): """ Load the given ui file relative to this package """ fullPath = os.path.join(modulePath(True), path) LOG.debug(fullPath) if not os.path.isfile(fullPath): raise ValueError('ui file not found: {0}'.format(fullPath)) loader = QUiLoader() file_ = QFile(fullPath) file_.open(QFile.ReadOnly) widget = loader.load(file_, parent) attachUi(widget, parent) file_.close() return widget
def createWidget(self, class_name, parent=None, name=''): # don't create the top-level widget, if a base instance is set if self._base_instance and not parent: return self._base_instance if class_name in self._custom_widgets: widget = self._custom_widgets[class_name](parent) else: widget = QUiLoader.createWidget(self, class_name, parent, name) if str(type(widget)).find(self.class_aliases.get(class_name, class_name)) < 0: sys.modules['QtCore'].qDebug( str('PySide.loadUi(): could not find widget ' 'class "%s", defaulting to "%s"' % ( class_name, type(widget))) ) if self._base_instance: setattr(self._base_instance, name, widget) return widget
def createWidget(self, class_name, parent=None, name=''): """ Function that is called for each widget defined in ui file, overridden here to populate baseinstance instead. """ if parent is None and self.baseinstance: # supposed to create the top-level widget, return the base instance # instead return self.baseinstance else: if class_name in self.availableWidgets(): # create a new widget for child widgets widget = QUiLoader.createWidget(self, class_name, parent, name) else: # if not in the list of availableWidgets, # must be a custom widget # this will raise KeyError if the user has not supplied the # relevant class_name in the dictionary, or TypeError, if # customWidgets is None try: widget = self.customWidgets[class_name](parent) except (TypeError, KeyError): raise Exception('No custom widget ' + class_name + ' found in customWidgets param of' + 'UiLoader __init__.') if self.baseinstance: # set an attribute for the new child widget on the base # instance, just like PyQt4.uic.loadUi does. setattr(self.baseinstance, name, widget) # this outputs the various widget names, e.g. # sampleGraphicsView, dockWidget, samplesTableView etc. # print(name) return widget
def __init__(self, *args, **kwargs): super(ReconManager, self).__init__(*args, **kwargs) queue_ui = QUiLoader().load('xicam/gui/tomographyqueue.ui') self.queue_form = QtGui.QStackedWidget() queue_ui.functionsList.setAlignment(QtCore.Qt.AlignBottom) queue_ui.moveDownButton.setToolTip('Move selected job down in queue') queue_ui.moveUpButton.setToolTip('Move selected job up in queue') self.manager = fw.FeatureManager( queue_ui.functionsList, self.queue_form, blank_form='Click items below to see reconstruction jobs on queue.' ) queue_ui.moveDownButton.clicked.connect(self.moveDown) queue_ui.moveUpButton.clicked.connect(self.moveUp) self.setOrientation(QtCore.Qt.Vertical) self.addWidget(self.queue_form) self.addWidget(queue_ui) # queue for reconstructions self.recon_queue = deque()
class IDASynergyCommitUI(QWidget): def __init__(self, cb_ok, cb_fail): super(IDASynergyCommitUI, self).__init__() self.loader = QUiLoader() self.initUI() self.ui.buttonBox.accepted.connect(cb_ok) self.ui.buttonBox.rejected.connect(cb_fail) def set_controls(self, updated_files): for to_update in updated_files: item = QListWidgetItem('[%s] %s' % to_update) item.setFlags(item.flags() | Qt.ItemIsUserCheckable) #if to_update[0] == "U": # item.setCheckState(Qt.Unchecked) #else: item.setCheckState(Qt.Checked) self.ui.listFiles.addItem(item) def get_dialog_values(self): listitem_re = re.compile("\[(\w)\]\ (.*)") listItems = [] for i in range(self.ui.listFiles.count()): item = self.ui.listFiles.item(i) checked = item.checkState() == Qt.Checked splitted = listitem_re.findall(item.text())[0] listItems.append((checked, splitted[0], splitted[1])) return self.ui.commitMessage.toPlainText(), listItems def do_modal(self): self.ui.show() #self.ui.exec_() return 0 def clear_controls(self): self.ui.listFiles.clear() @dialog() def initUI(self): self.ui = self.loader.load("commit.ui")
def createWidget(self, class_name, parent=None, name=''): """ Function that is called for each widget defined in ui file, overridden here to populate baseinstance instead. """ if parent is None and self.baseinstance: # supposed to create the top-level widget, return the base # instance instead return self.baseinstance else: # For some reason, Line is not in the list of available # widgets, but works fine, so we have to special case it here. if class_name in self.availableWidgets( ) or class_name == 'Line': # create a new widget for child widgets widget = QUiLoader.createWidget( self, class_name, parent, name) else: # If not in the list of availableWidgets, must be a custom # widget. This will raise KeyError if the user has not # supplied the relevant class_name in the dictionary or if # customWidgets is empty. try: widget = self.customWidgets[class_name](parent) except KeyError: raise Exception('No custom widget ' + class_name + ' ' 'found in customWidgets') if self.baseinstance: # set an attribute for the new child widget on the base # instance, just like PyQt4.uic.loadUi does. setattr(self.baseinstance, name, widget) return widget
def createWidget(self, class_name, parent=None, name=''): """ Function that is called for each widget defined in ui file, overridden here to populate baseinstance instead. """ if parent is None and self.baseinstance: return self.baseinstance else: if class_name in self.availableWidgets(): # create a new widget for child widgets widget = QUiLoader.createWidget(self, class_name, parent, name) else: try: widget = self.customWidgets[class_name](parent) except (TypeError, KeyError) as e: raise Exception( 'No custom widget ' + class_name + ' found in customWidgets param of UiLoader __init__.') if self.baseinstance: setattr(self.baseinstance, name, widget) return widget
def __init__(self, remotename='SPOT', parent=None): super(LoginDialog, self).__init__(parent) if remotename not in self.REMOTE_NAMES: raise ValueError('Remote must be one of %s, not %s' % (self.REMOTE_NAMES, remotename)) self.ui = QUiLoader().load('xicam/gui/login_widget.ui', self) self.ui.stackedWidget.setCurrentWidget(self.ui.login_page) self.ui.pass_box.setEchoMode(QtGui.QLineEdit.Password) self.ui.login_button.clicked.connect(self.handleLogin) self.ui.pass_box.returnPressed.connect(self.handleLogin) self.ui.host_box.returnPressed.connect(self.handleLogin) self.setStyleSheet('background-color:#111111;') self.hide() l = QtGui.QVBoxLayout() l.setContentsMargins(0, 0, 0, 0) l.addWidget(self.ui) self.setLayout(l) self._login_slot = None
def initialise_GUI(self): # Create DDS Output objects dds_prop = {'dds 0':{'freq':{'base_unit': 'Hz', 'min': 0.5e9, 'max': 10e9, 'step': 1e6, 'decimals': 3}, 'gate':{} } } # Create the output objects self.create_dds_outputs(dds_prop) # Create widgets for output objects dds_widgets,ao_widgets,do_widgets = self.auto_create_widgets() # and auto place the widgets in the UI self.auto_place_widgets(("DDS Outputs",dds_widgets)) self.status_ui = QUiLoader().load(os.path.join(os.path.dirname(os.path.realpath(__file__)),'phasematrixquicksyn.ui')) self.get_tab_layout().addWidget(self.status_ui) self.status_ui.ref_button.clicked.connect(self.update_reference_out) self.status_ui.blanking_button.clicked.connect(self.update_blanking) self.status_ui.lock_recovery_button.clicked.connect(self.update_lock_recovery) # Store the COM port to be used self.address = str(self.settings['connection_table'].find_by_name(self.settings["device_name"]).BLACS_connection) # Create and set the primary worker self.create_worker("main_worker",QuickSynWorker,{'address':self.address}) self.primary_worker = "main_worker" # Set the capabilities of this device self.supports_remote_value_check(True) self.supports_smart_programming(False) self.statemachine_timeout_add(2000, self.status_monitor)
def initUI(self): self.ui = QUiLoader().load(s.PATH_DOCTOR_DIALOG_NEWPATIENT, self) self.dateEdit = self.ui.findChild(QDateEdit, "Date")
from PySide.QtGui import QApplication, QPushButton, QScrollArea, QHBoxLayout from PySide.QtUiTools import QUiLoader from instrumental.drivers.cameras import uc480 from instrumental import gui if __name__ == '__main__': cam = uc480.get_camera(serial='4002856484') cam.open(num_bufs=2) cam.load_stored_parameters(1) cam2 = uc480.get_camera(serial='4002862589') cam2.open(num_bufs=2) cam2.load_stored_parameters(1) loader = QUiLoader() app = QApplication(sys.argv) ui = loader.load('live_gui.ui') scrollarea = ui.findChild(QScrollArea, 'scrollArea') camview = gui.DrawableCameraView(cam) scrollarea.setWidget(camview) camview2 = gui.CameraView(cam2) hbox = ui.findChild(QHBoxLayout, 'horizontalLayout') hbox.insertWidget(0, camview2) fnames = ['Side.jpg', 'Ruler.jpg', 'Top.jpg'] fnames = [os.path.join('images', fname) for fname in fnames] camview.set_overlays(fnames)
class NewAppointmentDialog(QDialog): def __init__(self, user, case_id, parent=None): QDialog.__init__(self, None) posX, posY, sizeW, sizeH = s.GEOMETRY_DIALOG_NEW_PATIENT self.setGeometry(posX, posY, sizeW, sizeH) self.user = user self.parent = parent self.case_id = case_id self.returnVal = False self.initUI() self.initLayout() self.initButton() self.setDateEdit() self.part_basic_info = [] self.part_appointment = [] self.part_extra_info = [] self.forDev() def initUI(self): self.ui = QUiLoader().load(s.PATH_DOCTOR_DIALOG_NEWPATIENT, self) self.dateEdit = self.ui.findChild(QDateEdit, "Date") def initLayout(self): layout = QGridLayout() layout.addWidget(self.ui) self.setLayout(layout) def initButton(self): self.b_save = self.ui.findChild(QPushButton, "button_save") self.b_cancel = self.ui.findChild(QPushButton, "button_cancel") self.b_save.clicked.connect(self.save) self.b_cancel.clicked.connect(self.cancel) def setDateEdit(self): self.dateEdit.setCalendarPopup(True) self.dateEdit.calendarWidget().installEventFilter(self) self.dateEdit.calendarWidget().setFirstDayOfWeek(Qt.Monday) def eventFilter(self, obj, event): if obj == self.dateEdit.calendarWidget() and event.type( ) == QEvent.Show: pos = self.dateEdit.mapToGlobal( self.dateEdit.geometry().bottomRight()) self.dateEdit.calendarWidget().window().move(pos.x(), pos.y()) return False def forDev(self): self.getNumberCase() ui = self.ui ui.AN.setText(self.case_id) count = self.case_id[-1] ui.PIC.setText("PIC " + count) ui.Name.setText("test Eii" + count) ui.Age.setText("20" + count) ui.Phone.setText("097124919" + count) ui.Pre_OD.document().setPlainText("Pre_OD " + count) ui.Plan.document().setPlainText("Plan " + count) ui.Underlying.document().setPlainText("Underlying " + count) ui.Treatment.document().setPlainText("Treatment " + count) ui.Note.document().setPlainText("Note " + count) def getNumberCase(self): self.case_id = str(int(self.parent.getCurrentCaseID()) + 1) def getData(self): ui = self.ui #["OPD", "AN", "Pic", "Name", "Age", "Phone"] self.part_basic_info.clear() self.part_basic_info.append(ui.OPD.currentText()) self.part_basic_info.append(ui.AN.text()) self.part_basic_info.append(ui.PIC.text()) self.part_basic_info.append(ui.Name.text()) self.part_basic_info.append(int(ui.Age.text())) self.part_basic_info.append(ui.Phone.text()) self.case_id = int(self.parent.getCurrentCaseID()) + 1 self.part_basic_info.append(self.case_id) #"Type", "Date", "Time" self.part_appointment.clear() self.part_appointment.append(ui.Type.currentText()) self.part_appointment.append(ui.Date.text()) self.part_appointment.append(ui.Time.currentText()) #"Pre_OD", "Plan", "Underlying", "Treatment", "Note" self.part_extra_info.clear() self.part_extra_info.append(ui.Pre_OD.toPlainText()) self.part_extra_info.append(ui.Plan.toPlainText()) self.part_extra_info.append(ui.Underlying.toPlainText()) self.part_extra_info.append(ui.Treatment.toPlainText()) self.part_extra_info.append(ui.Note.toPlainText()) def save(self): self.getData() # check valid same time date docID if self.parent.appointmentValid(self.part_appointment[1], self.part_appointment[2], self.user): #check AN and Name is the same [AN, patient_name] if self.parent.oldPatientValid(self.part_basic_info[1], self.part_basic_info[3]): self.returnVal = True pre_pre_report = [self.part_basic_info, self.part_extra_info] oldPatient = PatientClass.Patient(pre_pre_report) newAppointment = AppointmentClass.Appointment( self.case_id, self.part_appointment, self.user, oldPatient) self.parent.editPatient(oldPatient) self.parent.addNewAppointment(newAppointment) self.close() else: error = QErrorMessage() error.showMessage("Wrong information") error.setWindowTitle("Error!!!") error.exec_() else: #not valid appointment error = QErrorMessage() error.showMessage("Invalid Appointment Time") error.setWindowTitle("Error!!!") error.exec_() def cancel(self): title = "New Patient is canceling" textInfo = "Your entered information has not been saved." dialog = ConfirmMsgClass.ConfirmYesNo(title, textInfo) if dialog.ans == True: self.close() else: pass
def check_remote_values(self): self._last_remote_values = yield(self.queue_work(self._primary_worker,'check_remote_values')) for worker in self._secondary_workers: if self._last_remote_values: returned_results = yield(self.queue_work(worker,'check_remote_values')) self._last_remote_values.update(returned_results) # compare to current front panel values and prompt the user if they don't match # We compare to the last_programmed values so that it doesn't get confused if the user has changed the value on the front panel # and the program_manual command is still queued up # If no results were returned, raise an exception so that we don't keep calling this function over and over again, # filling up the text box with the same error, eventually consuming all CPU/memory of the PC if not self._last_remote_values or type(self._last_remote_values) != type({}): raise Exception('Failed to get remote values from device. Is it still connected?') # A variable to indicate if any of the channels have a changed value overall_changed = False # A place to store radio buttons in self._changed_radio_buttons = {} # Clean up the previously used layout while not self._ui.changed_layout.isEmpty(): item = self._ui.changed_layout.itemAt(0) # This is the only way I could make the widget actually be removed. # using layout.removeItem/removeWidget causes the layout to still draw the old item in its original space, and # then draw new items over the top of the old. Very odd behaviour, could be a windows 8 bug I suppose! item.widget().setParent(None) #TODO: somehow maintain the state of the radio buttons for specific channels between refreshes of this changed dialog. # TODO: Use the proper sort algorithm as defined for placing widgets to order this prompt # We expect a dictionary of channel:value pairs for channel in sorted(self._last_remote_values): remote_value = self._last_remote_values[channel] if channel not in self._last_programmed_values: raise RuntimeError('The worker function check_remote_values for device %s is returning data for channel %s but the BLACS tab is not programmed to handle this channel'%(self.device_name,channel)) # A variable to indicate if this channel has changed changed = False if channel in self._DDS: front_value = self._last_programmed_values[channel] # format the entries for the DDS object correctly, then compare front_values_formatted = {} remote_values_formatted = {} for sub_chnl in front_value: if sub_chnl not in remote_value: raise RuntimeError('The worker function check_remote_values has not returned data for the sub-channel %s in channel %s'%(sub_chnl,channel)) if sub_chnl == 'gate': front_values_formatted[sub_chnl] = str(bool(int(front_value[sub_chnl]))) remote_values_formatted[sub_chnl] = str(bool(int(remote_value[sub_chnl]))) else: decimals = self._DDS[channel].__getattribute__(sub_chnl)._decimals front_values_formatted[sub_chnl] = ("%."+str(decimals)+"f")%front_value[sub_chnl] remote_values_formatted[sub_chnl] = ("%."+str(decimals)+"f")%remote_value[sub_chnl] if front_values_formatted[sub_chnl] != remote_values_formatted[sub_chnl]: changed = True if changed: ui = QUiLoader().load(os.path.join(os.path.dirname(os.path.realpath(__file__)),'tab_value_changed_dds.ui')) ui.channel_label.setText(self._DDS[channel].name) for sub_chnl in front_value: ui.__getattribute__('front_%s_value'%sub_chnl).setText(front_values_formatted[sub_chnl]) ui.__getattribute__('remote_%s_value'%sub_chnl).setText(remote_values_formatted[sub_chnl]) # Hide unused sub_channels of this DDS for sub_chnl in self._DDS[channel].get_unused_subchnl_list(): ui.__getattribute__('front_%s_value'%sub_chnl).setVisible(False) ui.__getattribute__('front_%s_label'%sub_chnl).setVisible(False) ui.__getattribute__('remote_%s_value'%sub_chnl).setVisible(False) ui.__getattribute__('remote_%s_label'%sub_chnl).setVisible(False) elif channel in self._DO: # This is an easy case! front_value = str(bool(int(self._last_programmed_values[channel]))) remote_value = str(bool(int(remote_value))) if front_value != remote_value: changed = True ui = QUiLoader().load(os.path.join(os.path.dirname(os.path.realpath(__file__)),'tab_value_changed.ui')) ui.channel_label.setText(self._DO[channel].name) ui.front_value.setText(front_value) ui.remote_value.setText(remote_value) elif channel in self._AO: # A intermediately complicated case! front_value = ("%."+str(self._AO[channel]._decimals)+"f")%self._last_programmed_values[channel] remote_value = ("%."+str(self._AO[channel]._decimals)+"f")%remote_value if front_value != remote_value: changed = True ui = QUiLoader().load(os.path.join(os.path.dirname(os.path.realpath(__file__)),'tab_value_changed.ui')) ui.channel_label.setText(self._AO[channel].name) ui.front_value.setText(front_value) ui.remote_value.setText(remote_value) else: raise RuntimeError('device_base_class.py is not programmed to handle channel types other than DDS, AO and DO in check_remote_values') if changed: overall_changed = True # Add the changed widget for this channel to a layout! self._ui.changed_layout.addWidget(ui) # save the radio buttons so that we can access their state later! self._changed_radio_buttons[channel] = ui.use_remote_values if overall_changed: # TODO: Disable all widgets for this device, including virtual device widgets...how do I do that????? # Probably need to add a disable/enable method to analog/digital/DDS widgets that disables the widget and is orthogonal to the lock/unlock system # Should probably set a tooltip on the widgets too explaining why they are disabled! # self._device_widget.setSensitive(False) # show the remote_values_change dialog self._changed_widget.show() # Add an "apply" button and link to on_resolve_value_inconsistency button = QPushButton("Apply") button.clicked.connect(self.on_resolve_value_inconsistency) self._ui.changed_layout.addWidget(button)
class Gui(QObject): ''' ObsLight GUI main class. Keeps reference to the main window and to the ObsLightManager. ''' # signal to display a message in the status bar of the main window __messageSignal = Signal((str, int)) def __init__(self, qApplication): QObject.__init__(self) self.application = qApplication self.application.aboutToQuit.connect(self.__beforeQuitting) self.uiLoader = QUiLoader() # Need to set working directory in order to load icons self.uiLoader.setWorkingDirectory(UI_PATH) self.uiLoader.registerCustomWidget(ObsLightGuiMainWindow) self.uiLoader.registerCustomWidget(ObsLightGuiProgressDialog) # loaded in loadManager() self.splash = None self.__obsLightManager = None self.__obsProjectManager = None self.__micProjectsManager = None self.__logManager = None # loaded in __loadMainWindow() self.__mainWindow = None self.__mainWindowActionManager = None self.__statusBar = None # loaded in __createInfiniteProgressDialog() self.__infiniteProgress = None # loaded in __createProgressDialog() self.__progress = None # loaded in runWizard() self.__wizard = None def __beforeQuitting(self): """ Method called before the main QApplication quits. It disconnects the LogManager. """ self.__logManager.disconnectLogger() def loadWindow(self, uiFile, mainWindowAsParent=True, connectSlots=True): ''' Load a Window from UI file. ''' path = join(UI_PATH, uiFile) windowFile = QFile(path) windowFile.open(QIODevice.ReadOnly | QIODevice.Text) # Make all loaded windows children of mainWindow, except mainWindow itself window = self.uiLoader.load( windowFile, self.__mainWindow if mainWindowAsParent else None) windowFile.close() if connectSlots: QMetaObject.connectSlotsByName(window) return window def __loadMainWindow(self): self.__mainWindow = self.loadWindow(u"obsLightMain.ui") self.__mainWindowActionManager = MainWindowActionManager(self) self.__statusBar = self.__mainWindow.findChild(QStatusBar, u"mainStatusBar") self.__messageSignal.connect(self.__statusBar.showMessage) self.__loadGeometry() self.__mainWindow.show() def __loadGeometry(self): settings = QSettings("Intel_OTC", "obslightgui") propMap = { "mainWindow/geometry": self.__mainWindow.restoreGeometry, "mainWindow/state": self.__mainWindow.restoreState, "mainWindow/splitter2State": self.__mainWindow.splitter_2.restoreState, "mainWindow/splitter3State": self.__mainWindow.splitter_3.restoreState, "mainWindow/splitter4State": self.__mainWindow.splitter_4.restoreState, "mainWindow/splitter5State": self.__mainWindow.splitter_5.restoreState, "mainWindow/splitter6State": self.__mainWindow.splitter_6.restoreState, "mainWindow/splitterState": self.__mainWindow.splitter.restoreState, "mainWindow/splitterGeo": self.__mainWindow.splitter.restoreGeometry, "logWindow/geometry": self.__logManager.restoreGeometry } for propName, func in propMap.iteritems(): prop = settings.value(propName) if prop is not None: func(prop) def __saveGeometry(self): settings = QSettings("Intel_OTC", "obslightgui") propMap = { "mainWindow/geometry": self.__mainWindow.saveGeometry, "mainWindow/state": self.__mainWindow.saveState, "mainWindow/splitter2State": self.__mainWindow.splitter_2.saveState, "mainWindow/splitter3State": self.__mainWindow.splitter_3.saveState, "mainWindow/splitter4State": self.__mainWindow.splitter_4.saveState, "mainWindow/splitter5State": self.__mainWindow.splitter_5.saveState, "mainWindow/splitter6State": self.__mainWindow.splitter_6.saveState, "mainWindow/splitterState": self.__mainWindow.splitter.saveState, "mainWindow/splitterGeo": self.__mainWindow.splitter.saveGeometry, "logWindow/geometry": self.__logManager.saveGeometry } for propName, func in propMap.iteritems(): settings.setValue(propName, func()) def __createInfiniteProgressDialog(self): self.__infiniteProgress = self.loadWindow("obsLightProgress.ui", True) self.__infiniteProgress.connectButtons() self.__infiniteProgress.setMinimumDuration(500) self.__infiniteProgress.setWindowModality(Qt.WindowModal) self.__infiniteProgress.showCancelButton(False) # make the progress "infinite" self.__infiniteProgress.setRange(0, 0) showLogSlot = self.__mainWindowActionManager.actionLog.trigger self.__infiniteProgress.showLogButton.clicked.connect(showLogSlot) def __createProgressDialog(self): self.__progress = self.loadWindow("obsLightProgress.ui", True) self.__progress.connectButtons() self.__progress.setMinimumDuration(500) self.__progress.setWindowModality(Qt.WindowModal) # make the progress "finite" self.__progress.setRange(0, 1) showLogSlot = self.__mainWindowActionManager.actionLog.trigger self.__progress.showLogButton.clicked.connect(showLogSlot) @property def mainWindow(self): ''' Returns the main window object (may be None). ''' return self.__mainWindow def getInfiniteProgressDialog(self): ''' Get a reference to the main QProgressDialog. It is window-modal, has no cancel button and is infinite. ''' if self.__infiniteProgress is None: self.__createInfiniteProgressDialog() return self.__infiniteProgress def getProgressDialog(self): ''' Get a reference to a QProgressDialog instance. This progress dialog is window-modal and has a cancel button. ''' if self.__progress is None: self.__createProgressDialog() return self.__progress @property def manager(self): """ Get a reference to the unique ObsLightManager instance. """ return self.__obsLightManager def getLogManager(self): """ Get a reference to the LogManager instance. """ return self.__logManager def statusBarErrorCallback(self, error): ''' Display errors in the status bar of the main window. ''' if isinstance(error, OBSLightBaseError): self.sendStatusBarMessage(u"OBS Light error: %s" % error.msg, 30000) else: self.sendStatusBarMessage(u"Caught exception: %s" % str(error), 30000) def popupErrorCallback(self, error, traceback=None): ''' Display errors in a popup. Must be called from UI thread, or with a Qt signal. ''' exceptionToMessageBox(error, self.__mainWindow, traceback) def sendStatusBarMessage(self, message, timeout=0): ''' Display a message in the status bar of the main window. Timeout is in milliseconds. ''' self.__messageSignal.emit(message, timeout) def showLogWindow(self): """ Show the log window. If it is already opened, try to get it at foreground. """ self.__mainWindowActionManager.actionLog.trigger() def processEvents(self): """ Call QApplication.processEvents(). To be used if a function prevents the UI thread from returning to its event loop. """ self.application.processEvents() def refresh(self): self.__obsProjectManager.refresh() def setCurrentProject(self, projectName): self.__obsProjectManager.currentProject = projectName def runWizard(self): """ Run the OBS project creation wizard. If `autoSelectProject` is the name of an existing OBS Light project, go directly to the package selection page of the wizard. Returns the QWizard instance. """ self.__wizard = ConfigWizard(self) self.__wizard.accepted.connect(self.refresh) self.__wizard.show() return self.__wizard def runWizardToAddPackage(self, project, newPackage=False): self.__wizard = ConfigWizard(self) self.__wizard.accepted.connect(self.refresh) if newPackage: self.__wizard.skipToPackageCreation(project) else: self.__wizard.skipToPackageSelection(project) self.__wizard.show() return self.__wizard def runWizardToConfigureServer(self, parent=None, **prefilledValues): """ Run wizard and skip to server creation page. `parent` is the widget to use as parent for the wizard (None -> main window). `prefilledValues` allows to specify already known server configuration values. Possible keys for `prefilledValues`: "webUrl", "apiUrl", "repoUrl", "username", "password", "serverAlias". Returns the QWizard instance. """ self.__wizard = ConfigWizard(self, parent) self.__wizard.skipToServerCreation(**prefilledValues) self.__wizard.show() return self.__wizard def loadManager(self, methodToGetManager, *args, **kwargs): """ Show splash screen while calling `methodToGetManager(*args, **kwargs)` to get a reference to the ObsLightManager. """ pixmap = QPixmap(join(UI_PATH, "splashscreen.png")) self.splash = QSplashScreen(pixmap) self.splash.show() self.processEvents() self.splash.showMessage(u"Loading...", Qt.AlignBottom | Qt.AlignHCenter, QColor(u"white")) self.processEvents() self.__obsLightManager = methodToGetManager(*args, **kwargs) self.__logManager = LogManager(self) self.__loadMainWindow() self.__obsProjectManager = ObsProjectsManager(self) self.__micProjectsManager = MicProjectsManager(self) self.__mainWindow.callBeforeCloseEvent.append(self.__saveGeometry) self.__mainWindow.callBeforeCloseEvent.append(self.__logManager.close) self.splash.finish(self.mainWindow) def main(self): return self.application.exec_()
def __init__(self): self.loader = QUiLoader() for cls in ext_classes: self.loader.registerCustomWidget(cls)
def __init__(self, app): QtCore.QObject.__init__(self, app) print 'Gui:\t\t\t', QtGui.QApplication.instance().thread() QtGui.QFontDatabase.addApplicationFont("xicam/gui/zerothre.ttf") import plugins config.activate() self._pool = None # Load the gui from file self.app = app guiloader = QUiLoader() f = QtCore.QFile("xicam/gui/mainwindow.ui") f.open(QtCore.QFile.ReadOnly) self.ui = guiloader.load(f) f.close() # STYLE with open('xicam/gui/style.stylesheet', 'r') as f: style = f.read() app.setStyleSheet(qdarkstyle.load_stylesheet() + style) app.setAttribute(QtCore.Qt.AA_DontShowIconsInMenus, False) # INITIAL GLOBALS self.viewerprevioustab = -1 self.timelineprevioustab = -1 self.experiment = config.experiment() self.folderwatcher = watcher.newfilewatcher() self.plugins = [] # ACTIONS # Wire up action buttons self.ui.findChild(QtGui.QAction, 'actionOpen').triggered.connect(self.dialogopen) self.ui.findChild(QtGui.QAction, 'actionSettings').triggered.connect( self.settingsopen) self.ui.findChild(QtGui.QAction, 'actionQuit').triggered.connect( QtGui.QApplication.instance().quit) self.ui.actionExport_Image.triggered.connect(self.exportimage) # Grab status bar msg.statusbar = self.ui.statusbar pb = QtGui.QProgressBar() pb.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Ignored) msg.progressbar = pb pb.setAccessibleName('progressbar') msg.statusbar.addPermanentWidget(pb) pb.hide() msg.showMessage('Ready...') xglobals.statusbar = self.ui.statusbar # TODO: Deprecate this by replacing all statusbar calls with msg module # PLUG-INS placeholders = [ self.ui.viewmode, self.ui.sidemode, self.ui.bottommode, self.ui.toolbarmode, self.ui.leftmode ] plugins.initplugins(placeholders) plugins.plugins['MOTD'].instance.activate() plugins.base.fileexplorer.sigOpen.connect(self.openfiles) plugins.base.fileexplorer.sigFolderOpen.connect(self.openfolder) plugins.base.booltoolbar.actionTimeline.triggered.connect( plugins.base.filetree.handleOpenAction) pluginmode = plugins.widgets.pluginModeWidget(plugins.plugins) self.ui.modemenu.addWidget(pluginmode) self.ui.menubar.addMenu(plugins.buildactivatemenu(pluginmode)) # TESTING ## # self.openimages(['../samples/AgB_00016.edf']) # self.openimages(['/Users/rp/Data/LaB6_Ant1_dc002p.mar3450']) # self.calibrate() # self.updatepreprocessing() ## testmenu = QtGui.QMenu('Testing') testmenu.addAction('Single frame').triggered.connect(self.singletest) testmenu.addAction('Image stack').triggered.connect(self.stacktest) testmenu.addAction('Timeline').triggered.connect(self.timelinetest) testmenu.addAction('Tilt').triggered.connect(self.tilttest) self.ui.menubar.addMenu(testmenu) # DASK WORKFLOW # TODO turn this into a class # convert the following into a class self.sessions = ["localhost", "Andromeda", "Daint", "NERSC/Edison"] self.session_machines = [ "localhost", "andromeda.dhcp.lbl.gov", "148.187.1.7", "edison.nersc.gov" ] # self.session_address = ["localhost", socket.gethostbyname("andromeda.dhcp.lbl.gov"), "148.187.26.16", ""] self.session_address = [ "localhost", "andromeda.dhcp.lbl.gov", "148.187.26.16", "" ] self.session_exec = [ "", "/home/hari/runscript.sh", "/users/course79/runscript.sh", "/usr/common/graphics/visit/camera/runscript.sh" ] self.executors = [None, None, None, None] self.sessionmenu = QtGui.QMenu('Sessions') # comboBoxAction = ComboBoxAction("Active Session", self.sessionmenu); self.actionGroup = QtGui.QActionGroup(self.sessionmenu) for i in self.sessions: action = QtGui.QAction(i, self.sessionmenu, checkable=True) if i == "localhost": action.setChecked(True) action.triggered.connect(self.activesessionchanged) self.actionGroup.addAction(action) self.sessionmenu.addAction(action) # self.comboBoxAction.comboBox().activated.connect(self.activesessionchanged) # self.sessionmenu.addAction(comboBoxAction) self.ui.menubar.addMenu(self.sessionmenu) # self.daskLoop = client.dask_io_loop.DaskLoop() # try: # # create a local active executor # local_scheduler = client.dask_local_scheduler.LocalScheduler(self.daskLoop) # local_scheduler.execute() # self.executors[0] = local_scheduler # self.sessionmenu.setTitle("Active Session (localhost)") # client.dask_active_executor.active_executor = local_scheduler # except: # msg.logMessage("Issues connecting to localhost",msg.ERROR) # START PYSIDE MAIN LOOP # Show UI and end app when it closes self.ui.installEventFilter(self)
def create_dot_graph(root_ast, basic=False, scene=None, view=None, is_root=True): ''' Return a dot.AGraph item, from an ogAST.Process or child entry Set basic=True to generate a simple graph with at most one edge between two states and no diamond nodes is_root is set to False for nested diagrams ''' graph = dotgraph.AGraph(strict=False, directed=True) ret = {'graph': graph, 'children': {}, 'config': {}} diamond = 0 # Define the list of input signals including timers if is_root: input_signals = {sig['name'].lower() for sig in root_ast.input_signals} for each in root_ast.timers: input_signals.add(each) # TODO: add continuous signals else: # set by recursive caller: input_signals = root_ast.all_signals # Add the Connect parts below nested states for each in root_ast.content.states: for connect in each.connects: input_signals |= set(connect.connect_list) # valid_inputs: list of messages to be displayed in the statecharts # user can remove them from the file to make cleaner diagrams # config_params can be set to tune the call to graphviz valid_inputs = set() config_params = {} identifier = getattr(root_ast, "statename", root_ast.processName) #LOG.info("Statechart: rendering scene " + identifier) #LOG.info("Input signals from model: " + str (input_signals)) try: if not is_root: # Read config file only for the top-level diagram raise IOError with open(identifier + ".cfg", "r") as cfg_file: all_lines = (line.strip() for line in cfg_file.readlines()) for each in all_lines: split = each.split() if len(split) == 3 and split[0] == "cfg": config_params[split[1]] = split[2] elif each: valid_inputs.add(each.lower()) except IOError: valid_inputs = input_signals config_params = { "-Nfontsize": "10", "-Efontsize": "8", "-Gsplines": "curved", "-Gsep": "0.3", "-Gdpi": "72", "-Gstart": "random10", "-Goverlap": "scale", "-Nstyle": "rounded", "-Nshape": "record", "-Elen": "1" } else: LOG.info("Statechart settings read from " + identifier + ".cfg") LOG.info("... using signals: " + ", ".join(valid_inputs)) if scene and view: # Load and display a table for the user to filter out messages that # are not relevant to display on the statechart - and make it lighter # Do not repeat for substates (view is None and no cfg is saved) lock() def right(leftList, rightList): for each in leftList.selectedItems(): item = leftList.takeItem(leftList.row(each)) rightList.addItem(item) def left(leftList, rightList): for each in rightList.selectedItems(): item = rightList.takeItem(rightList.row(each)) leftList.addItem(item) loader = QUiLoader() ui_file = QtCore.QFile(":/statechart_cfg.ui") ui_file.open(QtCore.QFile.ReadOnly) dialog = loader.load(ui_file) dialog.setParent(view, QtCore.Qt.Dialog) okButton = dialog.findChild(QtGui.QPushButton, "okButton") rightButton = dialog.findChild(QtGui.QToolButton, "toRight") leftButton = dialog.findChild(QtGui.QToolButton, "toLeft") rightList = dialog.findChild(QtGui.QListWidget, "rightList") leftList = dialog.findChild(QtGui.QListWidget, "leftList") okButton.pressed.connect(dialog.accept) rightButton.pressed.connect(partial(right, leftList, rightList)) leftButton.pressed.connect(partial(left, leftList, rightList)) ui_file.close() rightList.addItems(list(valid_inputs)) leftList.addItems(list(input_signals - valid_inputs)) go = dialog.exec_() valid_inputs.clear() for idx in xrange(rightList.count()): valid_inputs.add(rightList.item(idx).text()) unlock() inputs_to_save = set(valid_inputs) for state in root_ast.mapping.viewkeys(): # create a new node for each state (including nested states) if state.endswith('START'): if len(state) > 5: label = state[0:-6] else: label = '' graph.add_node(state, label=label, shape='point', fixedsize='true', width=10.0 / 72.0) else: graph.add_node(state, label=state, shape='record', style='rounded') for each in [ term for term in root_ast.terminators if term.kind == 'return' ]: # create a new node for each RETURN statement (in nested states) ident = each.inputString.lower() or ' ' graph.add_node( ident, label='X', #ident, (no, otherwise size isn't ok) shape='square', width=1.0 / 72.0) # the AST does not contain a mapping the Connect parts below a state # Create it here on the spot connect_mapping = defaultdict(list) for each in root_ast.content.states: for stateName in each.statelist: connect_mapping[stateName.lower()].extend(each.connects) for state, inputs in chain(root_ast.mapping.viewitems(), root_ast.cs_mapping.viewitems(), connect_mapping.viewitems()): # Add edges transitions = \ inputs if not state.endswith('START') \ else [root_ast.transitions[inputs]] # Allow simplified graph, without diamonds and with at most one # transition from a given state to another target_states = defaultdict(set) for trans in transitions: source = state # transition label - there can be several inputs try: # Keep only message name, remove params and newlines # (newlines are not supported by graphviz) label, = re.match(r'([^(]+)', trans.inputString).groups() label = label.strip().replace('\n', ' ') except AttributeError: # START transition may have no inputString for each in root_ast.content.named_start: # each is of type ogAST.Start if each.transition == trans: label = each.inputString[:-6] break else: label = '' def find_terminators(trans): ''' Recursively find all NEXTSTATES and RETURN nodes ''' next_states = [ term for term in trans.terminators if term.kind in ('next_state', 'return') ] joins = [ term for term in trans.terminators if term.kind == 'join' ] for join in joins: # JOIN - Find corresponding label try: corr_label, = [ lab for lab in root_ast.content.floating_labels + root_ast.labels if lab.inputString.lower() == join.inputString.lower() ] except ValueError: LOG.error('Missing label: ' + join.inputString) else: # Don't recurse forever in case of livelock try: if corr_label.inputString != trans.inputString: next_states.extend( find_terminators(corr_label)) except AttributeError: # START transition -> no inputString pass return set(next_states) # Determine the list of terminators in this transition next_states = find_terminators(trans) if len(next_states) > 1 and not basic: # more than one terminator - add intermediate node graph.add_node(str(diamond), shape='diamond', fixedsize='true', width=15.0 / 72.0, height=15.0 / 72.0, label='') if label.lower() in valid_inputs or not label.strip(): graph.add_edge(source, str(diamond), label=label) inputs_to_save.add(label.lower()) source = str(diamond) label = '' diamond += 1 for term in next_states: if term.inputString.strip() == '-': target = state else: target = term.inputString.lower() or ' ' if basic: target_states[target] |= set(label.split(',')) else: labs = set(lab.strip() for lab in label.split(',') if lab.strip().lower() in valid_inputs | {""}) actual = ',\n'.join(labs) graph.add_edge(source, target, label=actual) inputs_to_save |= set(lab.lower() for lab in labs) for target, labels in target_states.viewitems(): sublab = [ lab.strip() for lab in labels if lab.strip().lower() in valid_inputs | {""} ] # Basic mode if sublab: label = ',\n'.join(sublab) inputs_to_save |= set(lab.lower() for lab in sublab) else: label = '' graph.add_edge(source, target, label=label) # Uncomment for debugging the generated dot graph: #with open('statechart.dot', 'w') as output: # output.write(graph.to_string()) #return graph if is_root: with open(identifier + ".cfg", "w") as cfg_file: for name, value in config_params.viewitems(): cfg_file.write("cfg {} {}\n".format(name, value)) for each in inputs_to_save: cfg_file.write(each + "\n") ret['config'] = config_params for each in root_ast.composite_states: # Recursively generate the graphs for nested states # Inherit from the list of signals from the higer level state #each.input_signals = root_ast.input_signals each.all_signals = valid_inputs ret['children'][each.statename] = create_dot_graph(each, basic, scene, is_root=False) return ret
def createWidget(self, clsname, parent=None, name=''): if clsname in self._custom_widgets: widget = self._custom_widgets[clsname](parent) else: widget = qloader.createWidget(self, clsname, parent, name) return widget
def load(self, uifile): self._parse_custom_widgets(uifile) self.uifile = uifile return QUiLoader.load(self, uifile)
def loadUI(ui_file, directory=location, parent_widget=None): """load .ui file as a QWidget""" loader = QUiLoader() loader.setWorkingDirectory(directory) return loader.load(ui_file, parent_widget) # parent widget are good for QMainWindow only
def initUI(self): path = 'Employee/Roommanager/View/Tab1_AllRoomUI.ui' #path = './View/Tab1_AllRoomUI.ui' self.tab1 = QUiLoader().load(path, self)
class Tab1AllRoom(QWidget): def __init__(self, parent=None): QWidget.__init__(self, None) self.parent = parent self.initUI() self.initLayout() self.initButton() self.initConnect() def initUI(self): path = 'Employee/Roommanager/View/Tab1_AllRoomUI.ui' #path = './View/Tab1_AllRoomUI.ui' self.tab1 = QUiLoader().load(path, self) def initLayout(self): layout = QGridLayout() layout.addWidget(self.tab1) self.setLayout(layout) def initButton(self): text = "Case no: " + "" + chr(10) \ + "Doctor: " + "" + chr(10) \ + "Patient: " + "" self.allRoomButton = [] self.allRoomButton.append(self.tab1.findChild(QPushButton, "buffer")) for i in range(1, Setting.NUMBER_OF_ROOM + 1): name_room = "room_" + str(i) button = self.tab1.findChild(QPushButton, name_room) button.setText(text) button.setStyleSheet("Text-align:left; Font:12px") self.allRoomButton.append(button) self.updateRoomUI(1, "0001", "Atichat", "Tiger") def initConnect(self): self.system = RoomSystemClass.RoomSystem() self.allRoomButton[1].clicked.connect( lambda: self.system.getDataOfRoom(1)) self.allRoomButton[2].clicked.connect( lambda: self.system.getDataOfRoom(2)) self.allRoomButton[3].clicked.connect( lambda: self.system.getDataOfRoom(3)) self.allRoomButton[4].clicked.connect( lambda: self.system.getDataOfRoom(4)) self.allRoomButton[5].clicked.connect( lambda: self.system.getDataOfRoom(5)) self.allRoomButton[6].clicked.connect( lambda: self.system.getDataOfRoom(6)) self.allRoomButton[7].clicked.connect( lambda: self.system.getDataOfRoom(7)) self.allRoomButton[8].clicked.connect( lambda: self.system.getDataOfRoom(8)) self.allRoomButton[9].clicked.connect( lambda: self.system.getDataOfRoom(9)) self.allRoomButton[10].clicked.connect( lambda: self.system.getDataOfRoom(10)) self.allRoomButton[11].clicked.connect( lambda: self.system.getDataOfRoom(11)) self.allRoomButton[12].clicked.connect( lambda: self.system.getDataOfRoom(12)) self.allRoomButton[13].clicked.connect( lambda: self.system.getDataOfRoom(13)) def updateRoomUI(self, NRoom, CaseNo, DName, PName): text = "Case no: " + CaseNo + chr(10) \ + "Doctor: " + DName + chr(10) \ + "Patient: " + PName self.allRoomButton[NRoom].setText(text) def updateStatus(self, NRoom, Status): pass def getAlert(self, NRoom): pass
def initUI(self): self.tab1 = QUiLoader().load('./Employee/Doctor/View/Tab1_CalendarUI.ui', self) self.calendar = self.tab1.findChild(QCalendarWidget, 'calendarWidget') self.labelDate = self.tab1.findChild(QLabel, 'label_date') self.taskView = self.tab1.findChild(QListView, 'listView')
class PySideDockTest(rv.rvtypes.MinorMode): "A python mode example that uses PySide" def orientCamera(self): "update projection matrix, especially when aspect ratio changes" glEnable(GL_CULL_FACE) glCullFace(GL_BACK) glPushAttrib(GL_TRANSFORM_BIT) # remember current GL_MATRIX_MODE # Set the camera lens so that we have a perspective viewing volume whose # horizontal bounds at the near clipping plane are -2..2 and vertical # bounds are -1.5..1.5. The near clipping plane is 1 unit from the camera # and the far clipping plane is 40 units away. glMatrixMode(GL_PROJECTION) glLoadIdentity() glFrustum(-2, 2, -1.5, 1.5, 1, 40) # Set up transforms so that the tetrahedron which is defined right at # the origin will be rotated and moved into the view volume. First we # rotate 70 degrees around y so we can see a lot of the left side. # Then we rotate 50 degrees around x to "drop" the top of the pyramid # down a bit. Then we move the object back 3 units "into the screen". glMatrixMode(GL_MODELVIEW) glLoadIdentity() glTranslatef(0, 0, -3) glRotatef(50, 1, 0, 0) glRotatef(rv.commands.frame() % 360, 0, 1, 0) glPopAttrib() # restore GL_MATRIX_MODE def renderGL(self): # ... render stuff in here ... # Draw a white grid "floor" for the tetrahedron to sit on. glColor3f(1.0, 1.0, 1.0) glBegin(GL_LINES) i = -2.5 while (i <= 2.5): glVertex3f(i, 0, 2.5) glVertex3f(i, 0, -2.5) glVertex3f(2.5, 0, i) glVertex3f(-2.5, 0, i) i += 0.25 glEnd() # Draw the tetrahedron. It is a four sided figure, so when defining it # with a triangle strip we have to repeat the last two vertices. glBegin(GL_TRIANGLE_STRIP) glColor3f(1, 1, 1) glVertex3f(0, 2, 0) glColor3f(1, 0, 0) glVertex3f(-1, 0, 1) glColor3f(0, 1, 0) glVertex3f(1, 0, 1) glColor3f(0, 0, 1) glVertex3f(0, 0, -1.4) glColor3f(1, 1, 1) glVertex3f(0, 2, 0) glColor3f(1, 0, 0) glVertex3f(-1, 0, 1) glEnd() def checkBoxPressed(self, checkbox, prop): def F(): try: if checkbox.isChecked(): if self.rvSessionQObject is not None: self.rvSessionQObject.setWindowOpacity(1.0) rv.commands.setIntProperty(prop, [1], True) else: if self.rvSessionQObject is not None: self.rvSessionQObject.setWindowOpacity(0.5) rv.commands.setIntProperty(prop, [0], True) except: pass return F def dialChanged(self, index, last, spins, prop): def F(value): diff = float(value - last[index]) if diff < -180: diff = value - last[index] + 360 elif diff > 180: diff = value - last[index] - 360 diff /= 360.0 last[index] = float(value) try: p = rv.commands.getFloatProperty(prop, 0, 1231231) p[0] += diff if p[0] > spins[index].maximum(): p[0] = spins[index].maximum() if p[0] < spins[index].minimum(): p[0] = spins[index].minimum() spins[index].setValue(p[0]) rv.commands.setFloatProperty(prop, p, True) except: pass return F def spinChanged(self, index, spins, prop): def F(value): try: rv.commands.setFloatProperty(prop, [p], True) except: pass def F(): try: p = spins[index].value() rv.commands.setFloatProperty(prop, [p], True) except: pass return F def findSet(self, typeObj, names): array = [] for n in names: array.append(self.dialog.findChild(typeObj, n)) if array[-1] == None: print "Can't find", n return array def hookup(self, checkbox, spins, dials, prop, last): checkbox.released.connect( self.checkBoxPressed(checkbox, "%s.node.active" % prop)) for i in range(0, 3): dial = dials[i] spin = spins[i] propName = "%s.warp.k%d" % (prop, i + 1) dial.valueChanged.connect( self.dialChanged(i, last, spins, propName)) spin.valueChanged.connect(self.spinChanged(i, spins, propName)) last[i] = dial.value() def __init__(self): rv.rvtypes.MinorMode.__init__(self) self.init("pyside_example", None, None) self.loader = QUiLoader() uifile = QFile( os.path.join(self.supportPath(pyside_example, "pyside_example"), "control.ui")) uifile.open(QFile.ReadOnly) self.dialog = self.loader.load(uifile) uifile.close() self.enableCheckBox = self.dialog.findChild(QCheckBox, "enableCheckBox") # # To retrieve the current RV session window and # use it as a Qt QMainWindow, we do the following: self.rvSessionQObject = rv.qtutils.sessionWindow() # have to hold refs here so they don't get deleted self.radialDistortDials = self.findSet(QDial, ["k1Dial", "k2Dial", "k3Dial"]) self.radialDistortSpins = self.findSet( QDoubleSpinBox, ["k1SpinBox", "k2SpinBox", "k3SpinBox"]) self.lastRadialDistort = [0, 0, 0] self.hookup(self.enableCheckBox, self.radialDistortSpins, self.radialDistortDials, "#RVLensWarp", self.lastRadialDistort) def render(self, event): self.orientCamera() self.renderGL() def activate(self): rv.rvtypes.MinorMode.activate(self) self.dialog.show() def deactivate(self): rv.rvtypes.MinorMode.deactivate(self) self.dialog.hide()
def add_notification(self, notification_class): if notification_class in self._notifications: return False try: # instantiate the notification class # TODO: Do we need to pass anything in here? self._notifications[notification_class] = notification_class( self._BLACS) # get the widget widget = self._notifications[notification_class].get_widget() # get details on whether the widget can be closed or hidden properties = self._notifications[ notification_class].get_properties() # Function shortcuts show_func = lambda: self.show_notification(notification_class) hide_func = lambda: self.minimize_notification(notification_class) close_func = lambda: self.close_notification(notification_class) get_state = lambda: self.get_state(notification_class) # create layout/widget with appropriate buttons and the widget from the notification class ui = QUiLoader().load( os.path.join(os.path.dirname(os.path.realpath(__file__)), 'notification_widget.ui')) ui.hide_button.setVisible(bool(properties['can_hide'])) ui.hide_button.clicked.connect(hide_func) ui.close_button.setVisible(bool(properties['can_close'])) ui.close_button.clicked.connect(close_func) ui.widget_layout.addWidget(widget) #ui.hide() #TODO: Make the minimized widget ui2 = QUiLoader().load( os.path.join(os.path.dirname(os.path.realpath(__file__)), 'notification_minimized_widget.ui')) #ui2.hide() if not hasattr(self._notifications[notification_class], 'name'): self._notifications[ notification_class].name = notification_class.__name__ ui2.name.setText(self._notifications[notification_class].name) ui2.show_button.setVisible(bool( properties['can_hide'])) #If you can hide, you can also show ui2.show_button.clicked.connect(show_func) ui2.close_button.setVisible(bool(properties['can_close'])) ui2.close_button.clicked.connect(close_func) # pass the show/hide/close functions to the notfication class self._widgets[notification_class] = ui self._minimized_widgets[notification_class] = ui2 self._notifications[notification_class].set_functions( show_func, hide_func, close_func, get_state) except: # Cleanup # TODO: cleanup a little more if notification_class in self._notifications: del self._notifications[notification_class] return False # add the widgets, initially hidden ui.setVisible(False) ui2.setVisible(False) self._BLACS['ui'].notifications.addWidget(ui) self._BLACS['ui'].notifications_minimized.addWidget(ui2) return True
def __init__(self, custom_widget_types=[]): qloader.__init__(self) typedict = {} for each in custom_widget_types: typedict[each.__name__] = each self._custom_widgets = typedict
class SettingDialog(QDialog): def __init__(self, parent = None, settings = {}): super(SettingDialog, self).__init__(parent) self.tempSettings = copy.deepcopy(settings) self.ui = QUiLoader().load("./settingDialog.ui") self.setupUi() #self.slot1 = self.openSettingWidget(item = current, previousItem = previous) #self.ui.treeWidget.currentItemChanged.connect(lambda: self.openSettingWidget(self.ui.treeWidget.currentItem())) self.ui.treeWidget.currentItemChanged.connect(self.openSettingWidget) self.ui.buttonBox.accepted.connect(lambda: self.ui.accept()) self.ui.buttonBox.rejected.connect(lambda: self.ui.reject()) def setupUi(self): self.treeWidgetTopItems = [QTreeWidgetItem(["General"]), QTreeWidgetItem(["Data Set"]), QTreeWidgetItem(["Graph Set"])] self.ui.treeWidget.addTopLevelItems(self.treeWidgetTopItems) self.treeWidgetDataSetItems = list() self.treeWidgetDataSetItems.append(QTreeWidgetItem(["全般"])) i = 1 while i <= len(self.tempSettings["dataSet"]): key = "dataSet" + str(i) item = QTreeWidgetItem() item.setText(0, self.tempSettings["dataSet"][key]["title"]) item.setText(1, key) self.treeWidgetDataSetItems.append(item) i += 1 self.treeWidgetGraphSetItems = list() self.treeWidgetGraphSetItems.append(QTreeWidgetItem(["全般"])) i = 1 while i <= len(self.tempSettings["graphSet"]): key = "graphSet" + str(i) item = QTreeWidgetItem() item.setText(0, self.tempSettings["graphSet"][key]["title"]) item.setText(1, key) self.treeWidgetGraphSetItems.append(item) i += 1 self.treeWidgetTopItems[1].addChildren(self.treeWidgetDataSetItems) self.treeWidgetTopItems[2].addChildren(self.treeWidgetGraphSetItems) self.openSettingWidget(self.ui.treeWidget.topLevelItem(0), None) self.ui.setWindowTitle("設定") def openSettingWidget(self, item, previousItem): if previousItem: self.updateTempSetting(previousItem) if self.ui.treeWidget.indexOfTopLevelItem(item) == 0: self.widget = GeneralSettingWidget(generalSetting = self.tempSettings["general"], shortcutSetting = self.tempSettings["shortcut"]) self.ui.verticalLayout.itemAt(0).widget().deleteLater() self.ui.verticalLayout.insertWidget(0, self.widget.ui) return elif self.ui.treeWidget.indexOfTopLevelItem(item) == 1: self.widget = DataSetSettingWidget(dataSetSettings = self.tempSettings["dataSet"]) self.widget.dataSetSettingsChanged.connect(lambda: self.updataTreeWidgetItemsDataSet()) self.ui.verticalLayout.itemAt(0).widget().deleteLater() self.ui.verticalLayout.insertWidget(0, self.widget.ui) return elif self.ui.treeWidget.indexOfTopLevelItem(item) == 2: self.widget = GraphSetSettingWidget(graphSetSettings = self.tempSettings["graphSet"], dataSetSettings = self.tempSettings["dataSet"]) self.widget.graphSetSettingsChanged.connect(lambda: self.updataTreeWidgetItemsGraphSet()) self.ui.verticalLayout.itemAt(0).widget().deleteLater() self.ui.verticalLayout.insertWidget(0, self.widget.ui) return elif self.ui.treeWidget.indexOfTopLevelItem(item) == -1: if self.ui.treeWidget.indexOfTopLevelItem(item.parent()) == 1: if item.parent().indexOfChild(item) == 0: self.widget = DataSetSettingWidget(dataSetSettings = self.tempSettings["dataSet"]) self.widget.dataSetSettingsChanged.connect(lambda: self.updataTreeWidgetItemsDataSet()) else: self.widget = DataSettingWidget(dataSetSetting = self.tempSettings["dataSet"][item.text(1)]) self.ui.verticalLayout.itemAt(0).widget().deleteLater() self.ui.verticalLayout.insertWidget(0, self.widget.ui) return elif self.ui.treeWidget.indexOfTopLevelItem(item.parent()) == 2: if item.parent().indexOfChild(item) == 0: self.widget = GraphSetSettingWidget(graphSetSettings = self.tempSettings["graphSet"], dataSetSettings = self.tempSettings["dataSet"]) self.widget.graphSetSettingsChanged.connect(lambda: self.updataTreeWidgetItemsGraphSet()) else: self.widget = GraphSettingWidget(generalSetting = self.tempSettings["general"], graphSetSetting = self.tempSettings["graphSet"][item.text(1)], dataSetSetting = self.tempSettings["dataSet"]["dataSet" + str(self.tempSettings["graphSet"][item.text(1)]["dataSet"]["index"])]) self.ui.verticalLayout.itemAt(0).widget().deleteLater() self.ui.verticalLayout.insertWidget(0, self.widget.ui) return else: self.widget = QLabel("Eroor") else: self.widget = QLabel("Eroor") self.ui.verticalLayout.itemAt(0).widget().deleteLater() self.ui.verticalLayout.insertWidget(0, self.widget) def updateTempSetting(self, item): if self.ui.treeWidget.indexOfTopLevelItem(item) == 0: self.tempSettings["general"] = self.widget.getCurrentGeneralSetting() self.tempSettings["shortcut"] = self.widget.getCurrentShortcutSettings() return elif self.ui.treeWidget.indexOfTopLevelItem(item) == 1: self.tempSettings["dataSet"] = self.widget.getCurrentDataSetSettings() return elif self.ui.treeWidget.indexOfTopLevelItem(item) == 2: self.tempSettings["graphSet"] = self.widget.getCurrentGraphSetSettings() return elif self.ui.treeWidget.indexOfTopLevelItem(item) == -1: if self.ui.treeWidget.indexOfTopLevelItem(item.parent()) == 1: if item.parent().indexOfChild(item) == 0: self.tempSettings["dataSet"] = self.widget.getCurrentDataSetSettings() else: self.tempSettings["dataSet"]["dataSet" + str(item.parent().indexOfChild(item))] = self.widget.getCurrentDataSetting() return elif self.ui.treeWidget.indexOfTopLevelItem(item.parent()) == 2: if item.parent().indexOfChild(item) == 0: self.tempSettings["graphSet"] = self.widget.getCurrentGraphSetSettings() else: self.tempSettings["graphSet"]["graphSet" + str(item.parent().indexOfChild(item))]["graphs"] = self.widget.getCurrentGraphSettings() return def updataTreeWidgetItemsDataSet(self): self.tempSettings["dataSet"] = self.widget.getCurrentDataSetSettings() while self.ui.treeWidget.topLevelItem(1).childCount() > 1: self.ui.treeWidget.topLevelItem(1).takeChild(1) self.treeWidgetDataSetItems = list() i = 1 while i <= len(self.tempSettings["dataSet"]): key = "dataSet" + str(i) item = QTreeWidgetItem() item.setText(0, self.tempSettings["dataSet"][key]["title"]) item.setText(1, key) self.treeWidgetDataSetItems.append(item) i += 1 self.ui.treeWidget.topLevelItem(1).addChildren(self.treeWidgetDataSetItems) self.ui.treeWidget.expandItem(self.ui.treeWidget.topLevelItem(1)) def updataTreeWidgetItemsGraphSet(self): self.tempSettings["graphSet"] = self.widget.getCurrentGraphSetSettings() while self.ui.treeWidget.topLevelItem(2).childCount() > 1: self.ui.treeWidget.topLevelItem(2).takeChild(1) self.treeWidgetGraphSetItems = list() i = 1 while i <= len(self.tempSettings["graphSet"]): key = "graphSet" + str(i) item = QTreeWidgetItem() item.setText(0, self.tempSettings["graphSet"][key]["title"]) item.setText(1, key) self.treeWidgetGraphSetItems.append(item) i += 1 self.ui.treeWidget.topLevelItem(2).addChildren(self.treeWidgetGraphSetItems) self.ui.treeWidget.expandItem(self.ui.treeWidget.topLevelItem(2))
class CompileAndRestart(QDialog): def __init__(self, blacs, globals_files, connection_table_labscript, output_path, close_notification_func=None): QDialog.__init__(self, blacs['ui']) self.setAttribute( Qt.WA_DeleteOnClose, True) # make sure the dialog is deleted when the window is closed self.globals_files = globals_files self.labscript_file = connection_table_labscript self.output_path = output_path self.tempfilename = self.output_path.strip('.h5') + '.temp.h5' self.blacs = blacs self.close_notification_func = close_notification_func self.ui = QUiLoader().load( os.path.join(os.path.dirname(os.path.realpath(__file__)), 'compile_and_restart.ui')) self.output_box = OutputBox(self.ui.verticalLayout) self.ui.restart.setEnabled(False) # Connect buttons self.ui.restart.clicked.connect(self.restart) self.ui.compile.clicked.connect(self.compile) self.ui.cancel.clicked.connect(self.reject) self.ui.setParent(self) self.ui.show() self.show() self.compile() def closeEvent(self, event): if not self.ui.cancel.isEnabled(): event.ignore() else: event.accept() def on_activate_default(self, window): if self.button_restart.get_sensitive(): self.restart() elif self.button_compile.get_sensitive(): self.compile() def compile(self): self.ui.compile.setEnabled(False) self.ui.cancel.setEnabled(False) self.ui.restart.setEnabled(False) self.ui.label.setText('Recompiling connection table') runmanager.compile_labscript_with_globals_files_async( self.labscript_file, self.globals_files, self.tempfilename, self.output_box.port, self.finished_compiling) @inmain_decorator(True) def finished_compiling(self, success): self.ui.compile.setEnabled(True) self.ui.cancel.setEnabled(True) if success: self.ui.restart.setEnabled(True) self.ui.cancel.setEnabled(False) self.ui.label.setText('Compilation succeeded, restart when ready') try: os.remove(self.output_path) except OSError: # File doesn't exist, no need to delete then: pass try: os.rename(self.tempfilename, self.output_path) except OSError: self.output_box.output( 'Couldn\'t replace existing connection table h5 file. Is it open in another process?', red=True) self.ui.label.setText('Compilation failed.') self.ui.restart.setEnabled(False) os.remove(self.tempfilename) else: self.ui.restart.setEnabled(False) self.ui.label.setText( 'Compilation failed. Please fix the errors in the connection table (python file) and try again' ) try: os.remove(self.tempfilename) except Exception: pass def restart(self): #gobject.timeout_add(100, self.blacs.destroy) if self.close_notification_func: self.close_notification_func() QTimer.singleShot(100, self.blacs['ui'].close) self.accept() self.blacs['set_relaunch'](True)
def __init__(self, baseinstance): QUiLoader.__init__(self) self.baseinstance = baseinstance self._widgets = []
def __init__(self, instance): QUiLoader.__init__(self, instance) self._instance = instance
def __init__(self, baseinstance): QUiLoader.__init__(self, baseinstance) self.baseinstance = baseinstance