def __init__(self, parent = getMayaWindow()): super(FixJointModeWindow, self).__init__() QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling) #load UI file uiFile = QtCore.QFile(uiFilePath) uiFile.open(QtCore.QFile.ReadOnly) self.ui = QtUiTools.QUiLoader().load(uiFile,parentWidget = self) uiFile.close() uiFile = QtCore.QFile(uiFilePath) uiFile.open(QtCore.QFile.ReadOnly) self.helpUi = QtUiTools.QUiLoader().load(helpUiPath) uiFile.close() #load picture self.helpUi.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) self.helpUi.picture_LB.setPixmap(QtGui.QPixmap(helpPicPath)) #initial window self.minSize = QtCore.QSize(467, 507) self.setFixedSize(self.minSize) self.setWindowTitle("Fix Joint Mode") self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) self.ui.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) #connect signal to function self.ui.mode_Chk.stateChanged.connect(self.modeChanged) self.ui.debug_Chk.stateChanged.connect(self.debugMode) self.ui.addIK_Btn.clicked.connect(self.addIK) self.ui.showIK_Btn.clicked.connect(self.showIK) self.ui.defaultIK_Btn.clicked.connect(self.defaultIK) self.ui.clearIK_Btn.clicked.connect(self.clearIK) self.ui.sktPath_Btn.clicked.connect(self.importBrowser) self.ui.buttonGroup.buttonClicked.connect(self.pAxisBG) self.ui.buttonGroup_2.buttonClicked.connect(self.sAxisBG) self.ui.buttonGroup_3.buttonClicked.connect(self.sAxisOrientBG) self.ui.comboBox_1.currentIndexChanged.connect(self.pAxisBG) self.ui.comboBox_2.currentIndexChanged.connect(self.sAxisBG) self.ui.comboBox_3.currentIndexChanged.connect(self.sAxisOrientBG) self.ui.addMirror_Btn.clicked.connect(self.addMirror) self.ui.showMirror_Btn.clicked.connect(self.showMirror) self.ui.defaultMirror_Btn.clicked.connect(self.defaultMirror) self.ui.clearMirror_Btn.clicked.connect(self.clearMirror) self.ui.mirror_Btn.clicked.connect(self.mirror) self.ui.exportBrowse_Btn.clicked.connect(self.exportBrowser) self.ui.export_Btn.clicked.connect(self.exportBuilder) self.ui.tool_Btn.clicked.connect(self.OpenCreateRigUI) self.ui.help_Btn.clicked.connect(self.helpWindow) #set radio id self.ui.buttonGroup.setId(self.ui.radioButton_01,0) self.ui.buttonGroup.setId(self.ui.radioButton_02,1) self.ui.buttonGroup.setId(self.ui.radioButton_03,2) self.ui.buttonGroup_2.setId(self.ui.radioButton_11,0) self.ui.buttonGroup_2.setId(self.ui.radioButton_12,1) self.ui.buttonGroup_2.setId(self.ui.radioButton_13,2) self.ui.buttonGroup_3.setId(self.ui.radioButton_21,0) self.ui.buttonGroup_3.setId(self.ui.radioButton_22,1) self.ui.buttonGroup_3.setId(self.ui.radioButton_23,2) self.ui.buttonGroup_4.setId(self.ui.radioButton_31,0) self.ui.buttonGroup_4.setId(self.ui.radioButton_32,1) self.ui.buttonGroup_4.setId(self.ui.radioButton_33,2) self.initialAxis() orientHelper.fjm.switchMode(True)
def __init__(self, desktop): self.load_resource_file() self.root_window = QtGui.QMainWindow() self.root_window = QtUiTools.QUiLoader().load( QtCore.QFile("H3/GUI/QtDesigns/Main.ui"), desktop) self.rect = desktop.availableGeometry() rect2 = QtCore.QRect(self.rect.width() / 6, self.rect.height() / 6, self.rect.width() * 2 / 3, self.rect.height() * 2 / 3) self.root_window.setGeometry(rect2) self.locale = babel.Locale.parse(locale.getdefaultlocale()[0], "_") syncbutton = QtGui.QPushButton(QtGui.QIcon(":/images/H3.png"), _("Sync"), self.root_window) # noinspection PyUnresolvedReferences syncbutton.clicked.connect(self.sync) empty = QtGui.QWidget() empty.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.root_window.toolBar.addWidget(empty) self.root_window.toolBar.addWidget(syncbutton) prog = QtGui.QProgressBar() self.root_window.statusbar.addPermanentWidget(prog) self.root_window.show() while not H3Core.wizard_system_ready(): self.run_setup_wizard() LoginBox(self) self.current_screen = None base = H3Core.get_from_primary_key( Acd.WorkBase, H3Core.current_job_contract.work_base) user = H3Core.get_from_primary_key(Acd.User, H3Core.current_job_contract.user) self.root_window.setWindowTitle( _("{first} {last}, {job}, {base}").format( first=user.first_name, last=user.last_name, job=H3Core.current_job_contract.job_title, base=base.full_name)) actions_model = self.build_actions_menu() self.root_window.treeView.setModel(actions_model) self.root_window.treeView.expandAll() self.root_window.treeView.resizeColumnToContents(0) self.root_window.treeView.setFixedWidth( self.root_window.treeView.columnWidth(0) + 10) self.root_window.Actions.setFixedWidth( self.root_window.treeView.size().width() + 50) action_selector = self.root_window.treeView.selectionModel() # This allows keyboard navigation in the action bar action_selector.currentChanged.connect(self.ui_switcher) self.root_window.treeView.clicked.connect(self.ui_switcher)
def setWindowStyle(self): f = QtCore.QFile('style/style.qss') f.open(QtCore.QFile.ReadOnly | QtCore.QFile.Text) ts = QtCore.QTextStream(f) self.stylesheet = ts.readAll() self.setStyleSheet(self.stylesheet)
def handle(): "builds the HTML code of the start page" global iconbank, tempfolder # reuse stuff from previous runs to reduce temp dir clutter import Start if hasattr(Start, "iconbank"): iconbank = Start.iconbank if hasattr(Start, "tempfolder"): tempfolder = Start.tempfolder else: tempfolder = tempfile.mkdtemp(prefix="FreeCADStartThumbnails") # build the html page skeleton resources_dir = os.path.join(FreeCAD.getResourceDir(), "Mod", "Start", "StartPage") p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Start") template = p.GetString("Template", "") if template: html_filename = template else: html_filename = os.path.join(resources_dir, "StartPage.html") js_filename = os.path.join(resources_dir, "StartPage.js") css_filename = os.path.join(resources_dir, "StartPage.css") with open(html_filename, 'r') as f: HTML = f.read() with open(js_filename, 'r') as f: JS = f.read() with open(css_filename, 'r') as f: CSS = f.read() HTML = HTML.replace("JS", JS) HTML = HTML.replace("CSS", CSS) HTML = encode(HTML) # get the stylesheet if we are using one if FreeCAD.ParamGet( "User parameter:BaseApp/Preferences/Mod/Start").GetBool( "UseStyleSheet", False): qssfile = FreeCAD.ParamGet( "User parameter:BaseApp/Preferences/MainWindow").GetString( "StyleSheet", "") if qssfile: # Search for stylesheet in user, system and resources locations user = os.path.join(FreeCAD.getUserAppDataDir(), "Gui", "Stylesheets") system = os.path.join(FreeCAD.getResourceDir(), "Gui", "Stylesheets") resources = ":/stylesheets" res = False if QtCore.QFile.exists(os.path.join(user, qssfile)): path = os.path.join(user, qssfile) elif QtCore.QFile.exists(os.path.join(system, qssfile)): path = os.path.join(system, qssfile) elif QtCore.QFile.exists(os.path.join(resources, qssfile)): res = True path = os.path.join(resources, qssfile) else: path = None if path: if res: f = QtCore.QFile(path) if f.open(QtCore.QIODevice.ReadOnly | QtCore.QFile.Text): ALTCSS = encode(QtCore.QTextStream(f).readAll()) else: with open(path, 'r') as f: ALTCSS = encode(f.read()) HTML = HTML.replace( "<!--QSS-->", "<style type=\"text/css\">" + ALTCSS + "</style>") # turn tips off if needed if not FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Start" ).GetBool("ShowTips", True): HTML = HTML.replace("display: block; /* footnote tips display */", "display: none; /* footnote tips display */") # get FreeCAD version v = FreeCAD.Version() VERSIONSTRING = encode(TranslationTexts.T_VERSION + " " + v[0] + "." + v[1] + " " + TranslationTexts.T_BUILD + " " + v[2]) HTML = HTML.replace("VERSIONSTRING", VERSIONSTRING) # translate texts texts = [t for t in dir(TranslationTexts) if t.startswith("T_")] for text in texts: HTML = HTML.replace(text, encode(getattr(TranslationTexts, text))) # build a "create new" icon with the FreeCAD background color gradient if not "createimg" in iconbank: p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/View") c1 = gethexcolor(p.GetUnsigned("BackgroundColor2")) c2 = gethexcolor(p.GetUnsigned("BackgroundColor3")) gradient = QtGui.QLinearGradient(0, 0, 0, 128) gradient.setColorAt(0.0, QtGui.QColor(c1)) gradient.setColorAt(1.0, QtGui.QColor(c2)) i = QtGui.QImage(128, 128, QtGui.QImage.Format_RGB16) pa = QtGui.QPainter(i) pa.fillRect(i.rect(), gradient) pa.end() createimg = tempfile.mkstemp(dir=tempfolder, suffix='.png')[1] i.save(createimg) iconbank["createimg"] = createimg # build SECTION_RECENTFILES SECTION_RECENTFILES = encode("") rf = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/RecentFiles") rfcount = rf.GetInt("RecentFiles", 0) SECTION_RECENTFILES = encode("<h2>" + TranslationTexts.T_RECENTFILES + "</h2>") SECTION_RECENTFILES += "<ul>" SECTION_RECENTFILES += '<a href="LoadNew.py" title="' + encode( TranslationTexts.T_CREATENEW) + '">' SECTION_RECENTFILES += '<li class="icon">' if FreeCAD.ParamGet( "User parameter:BaseApp/Preferences/Mod/Start").GetBool( "NewFileGradient", False): SECTION_RECENTFILES += '<img src="file:///' + encode( iconbank["createimg"]) + '">' else: SECTION_RECENTFILES += '<img src="file:///' + os.path.join( resources_dir, "images/new_file_thumbnail.svg") + '">' SECTION_RECENTFILES += '<div class="caption">' SECTION_RECENTFILES += '<h4>' + encode( TranslationTexts.T_CREATENEW) + '</h4>' SECTION_RECENTFILES += '</div>' SECTION_RECENTFILES += '</li>' SECTION_RECENTFILES += '</a>' for i in range(rfcount): filename = rf.GetString("MRU%d" % (i)) SECTION_RECENTFILES += encode( buildCard(filename, method="LoadMRU.py?MRU=", arg=str(i))) SECTION_RECENTFILES += '</ul>' HTML = HTML.replace("SECTION_RECENTFILES", SECTION_RECENTFILES) # build SECTION_EXAMPLES SECTION_EXAMPLES = encode("") if FreeCAD.ParamGet( "User parameter:BaseApp/Preferences/Mod/Start").GetBool( "ShowExamples", True): SECTION_EXAMPLES = encode("<h2>" + TranslationTexts.T_EXAMPLES + "</h2>") SECTION_EXAMPLES += "<ul>" examples_path = FreeCAD.getResourceDir() + "examples" if os.path.exists(examples_path): examples = os.listdir(examples_path) for basename in examples: filename = FreeCAD.getResourceDir( ) + "examples" + os.sep + basename SECTION_EXAMPLES += encode( buildCard(filename, method="LoadExample.py?filename=")) SECTION_EXAMPLES += "</ul>" HTML = HTML.replace("SECTION_EXAMPLES", SECTION_EXAMPLES) # build SECTION_CUSTOM SECTION_CUSTOM = encode("") cfolder = FreeCAD.ParamGet( "User parameter:BaseApp/Preferences/Mod/Start").GetString( "ShowCustomFolder", "") if cfolder: if not os.path.isdir(cfolder): cfolder = os.path.dirname(cfolder) SECTION_CUSTOM = encode("<h2>" + os.path.basename(os.path.normpath(cfolder)) + "</h2>") SECTION_CUSTOM += "<ul>" for basename in os.listdir(cfolder): filename = os.path.join(cfolder, basename) SECTION_CUSTOM += encode( buildCard(filename, method="LoadCustom.py?filename=")) SECTION_CUSTOM += "</ul>" # hide the custom section tooltip if custom section is set (users know about it if they enabled it) HTML = HTML.replace("id=\"customtip\"", "id=\"customtip\" style=\"display:none;\"") HTML = HTML.replace("SECTION_CUSTOM", SECTION_CUSTOM) # build IMAGE_SRC paths HTML = HTML.replace( "IMAGE_SRC_USERHUB", 'file:///' + os.path.join(resources_dir, 'images/userhub.png')) HTML = HTML.replace( "IMAGE_SRC_POWERHUB", 'file:///' + os.path.join(resources_dir, 'images/poweruserhub.png')) HTML = HTML.replace( "IMAGE_SRC_DEVHUB", 'file:///' + os.path.join(resources_dir, 'images/developerhub.png')) HTML = HTML.replace( "IMAGE_SRC_MANUAL", 'file:///' + os.path.join(resources_dir, 'images/manual.png')) HTML = HTML.replace( "IMAGE_SRC_SETTINGS", 'file:///' + os.path.join(resources_dir, 'images/settings.png')) imagepath = 'file:///' + os.path.join(resources_dir, 'images/installed.png') imagepath = imagepath.replace( '\\', '/' ) # replace Windows backslash with slash to make the path javascript compatible HTML = HTML.replace("IMAGE_SRC_INSTALLED", imagepath) # build UL_WORKBENCHES wblist = [] UL_WORKBENCHES = '<ul class="workbenches">' FreeCAD.getResourceDir() for wb in sorted(FreeCADGui.listWorkbenches().keys()): if wb.endswith("Workbench"): wn = wb[:-9] else: wn = wb # fixes for non-standard names if wn == "flamingoTools": wn = "flamingo" elif wn == "Geodat": wn = "geodata" elif wn == "a2p": wn = "A2plus" elif wn == "ArchTexture": wn = "ArchTextures" elif wn == "CadQuery": wn = "cadquery_module" elif wn == "DefeaturingWB": wn = "Defeaturing" elif wn == "ksuWB": wn = "kicadStepUp" elif wn == "ManipulatorWB": wn = "Manipulator" elif wn == "PartOMagic": wn = "Part-o-magic" elif wn == "SM": wn = "sheetmetal" elif wn == "gear": wn = "FCGear" elif wn == "frame_": wn = "frame" elif wn == "None": continue wblist.append(wn.lower()) if wb in iconbank: img = iconbank[wb] else: img = os.path.join(FreeCAD.getResourceDir(), "Mod", wn, "Resources", "icons", wn + "Workbench.svg") if not os.path.exists(img): w = FreeCADGui.listWorkbenches()[wb] if hasattr(w, "Icon"): xpm = w.Icon if "XPM" in xpm: xpm = xpm.replace( "\n ", "\n" ) # some XPMs have some indent that QT doesn't like r = [ s[:-1].strip('"') for s in re.findall( "(?s)\{(.*?)\};", xpm)[0].split("\n")[1:] ] p = QtGui.QPixmap(r) p = p.scaled(24, 24) img = tempfile.mkstemp(dir=tempfolder, suffix='.png')[1] p.save(img) else: img = xpm else: img = os.path.join(resources_dir, "images/freecad.png") iconbank[wb] = img UL_WORKBENCHES += '<li>' UL_WORKBENCHES += '<img src="file:///' + iconbank[wb] + '"> ' UL_WORKBENCHES += '<a href="https://www.freecadweb.org/wiki/' + wn + '_Workbench">' + wn.replace( "ReverseEngineering", "ReverseEng") + '</a>' UL_WORKBENCHES += '</li>' UL_WORKBENCHES += '</ul>' HTML = HTML.replace("UL_WORKBENCHES", encode(UL_WORKBENCHES)) # Detect additional addons that are not a workbench try: import dxfLibrary except: pass else: wblist.append("dxf-library") try: import RebarTools except: pass else: wblist.append("reinforcement") try: import CADExchangerIO except: pass else: wblist.append("cadexchanger") HTML = HTML.replace("var wblist = [];", "var wblist = " + str(wblist) + ";") # set and replace colors and font settings p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Start") if p.GetString("BackgroundImage", ""): BACKGROUND = gethexcolor(p.GetUnsigned( "BackgroundColor1", 1331197183)) + " url(" + p.GetString( "BackgroundImage", "") + ")" else: BACKGROUND = gethexcolor(p.GetUnsigned("BackgroundColor1", 1331197183)) # linear gradient not supported by QT "linear-gradient("+gethexcolor(p.GetUnsigned("BackgroundColor1",1331197183))+","+gethexcolor(p.GetUnsigned("BackgroundColor2",2141107711))+")" LINKCOLOR = gethexcolor(p.GetUnsigned("LinkColor", 65535)) BASECOLOR = gethexcolor(p.GetUnsigned("PageColor", 4294967295)) BOXCOLOR = gethexcolor(p.GetUnsigned("BoxColor", 3722305023)) TEXTCOLOR = gethexcolor(p.GetUnsigned("PageTextColor", 255)) BGTCOLOR = gethexcolor(p.GetUnsigned("BackgroundTextColor", 4294703103)) SHADOW = "#888888" if QtGui.QColor(BASECOLOR).valueF( ) < 0.5: # dark page - we need to make darker shadows SHADOW = "#000000" FONTFAMILY = encode(p.GetString("FontFamily", "Arial,Helvetica,sans")) if not FONTFAMILY: FONTFAMILY = "Arial,Helvetica,sans" FONTSIZE = p.GetInt("FontSize", 13) HTML = HTML.replace("BASECOLOR", BASECOLOR) HTML = HTML.replace("BOXCOLOR", BOXCOLOR) HTML = HTML.replace("LINKCOLOR", LINKCOLOR) HTML = HTML.replace("TEXTCOLOR", TEXTCOLOR) HTML = HTML.replace("BGTCOLOR", BGTCOLOR) HTML = HTML.replace("BACKGROUND", BACKGROUND) HTML = HTML.replace("FONTFAMILY", FONTFAMILY) HTML = HTML.replace("FONTSIZE", str(FONTSIZE) + "px") # enable web access if permitted if FreeCAD.ParamGet( "User parameter:BaseApp/Preferences/Mod/Start").GetBool( "AllowDownload", False): HTML = HTML.replace("var allowDownloads = 0;", "var allowDownloads = 1;") # enable or disable forum if FreeCAD.ParamGet( "User parameter:BaseApp/Preferences/Mod/Start").GetBool( "ShowForum", False): HTML = HTML.replace("var showForum = 0;", "var showForum = 1;") HTML = HTML.replace("display: none; /* forum display */", "display: block; /* forum display */") # enable or disable notepad if FreeCAD.ParamGet( "User parameter:BaseApp/Preferences/Mod/Start").GetBool( "ShowNotes", False): HTML = HTML.replace("display: none; /* notes display */", "display: block; /* notes display */") HTML = HTML.replace("width: 100%; /* thumbs display */", "width: 70%; /* thumbs display */") # store variables for further use Start.iconbank = iconbank Start.tempfolder = tempfolder # make sure we are always returning unicode # HTML should be a str-object and therefore: # - for py2 HTML is a bytes object and has to be decoded to unicode # - for py3 HTML is already a unicode object and the next 2 lines can be removed # once py2-support is removed. if isinstance(HTML, bytes): HTML = HTML.decode("utf8") return HTML
def _initialize_dark_look_and_feel(self): """ Initializes a standard toolkit look and feel using a combination of QPalette and stylesheets. If your engine is running inside an environment which already has a dark style defined, do not call this method. The Toolkit apps are designed to work well with most dark themes. However, if you are for example creating your own QApplication instance you can execute this method to but the session into Toolkit's standard dark mode. This will initialize the plastique style and set it up with a standard dark palette and supporting stylesheet. Apps and UIs can then extend this further by using further css. Due to restrictions in QT, this needs to run after a QApplication object has been instantiated. """ from .qt import QtGui, QtCore this_folder = os.path.abspath(os.path.dirname(__file__)) # initialize our style QtGui.QApplication.setStyle("plastique") # Read in a serialized version of a palette # this file was generated in the following way: # # Inside of maya 2014, the following code was executed: # # from PySide import QtGui, QtCore # app = QtCore.QCoreApplication.instance() # fh = QtCore.QFile("/tmp/palette.dump") # fh.open(QtCore.QIODevice.WriteOnly) # out = QtCore.QDataStream(fh) # out.__lshift__( app.palette() ) # fh.close() # # When we load this up in our engine, we will get a look # and feel similar to that of maya. try: # open palette file palette_file = os.path.join(this_folder, "qt", "dark_palette.qpalette") fh = QtCore.QFile(palette_file) fh.open(QtCore.QIODevice.ReadOnly); file_in = QtCore.QDataStream(fh) # deserialize the palette # (store it for GC purposes) self._dark_palette = QtGui.QPalette() file_in.__rshift__(self._dark_palette) fh.close() # set the std selection bg color to be 'shotgun blue' self._dark_palette.setBrush(QtGui.QPalette.Highlight, QtGui.QBrush(QtGui.QColor("#30A7E3"))) self._dark_palette.setBrush(QtGui.QPalette.HighlightedText, QtGui.QBrush(QtGui.QColor("#FFFFFF"))) # and associate it with the qapplication QtGui.QApplication.setPalette(self._dark_palette) except Exception, e: self.log_error("The standard toolkit dark palette could not be set up! The look and feel of your " "toolkit apps may be sub standard. Please contact support. Details: %s" % e)
splash.show() app.processEvents() # Database.connect(host="localhost", # databaseName="salaryManagement_test_1", # username="******", # password="******") Database.connect(host="remotemysql.com", username="******", password="******", databaseName="ll703lm6tX") w = MainWindow() styleSheetFile = QtCore.QFile("styleSheet/flatStyleSheet.css") styleSheetFile.open(QtCore.QIODevice.ReadOnly) w.setStyleSheet(str(styleSheetFile.readAll())) w.show() splash.finish(w) except mysql.connector.Error as e: splash.close() ShowMysqlError(e) sys.exit() # except Exception as e: # splash.close() # msg = QMessageBox(QMessageBox.Critical, "Error", "Unexpected error occured!\n" + str(e))
def OnCreate(self, form): self.parent = self.FormToPySideWidget(form) self.wid = QtGui.QWidget() binaryUIPath = os.path.dirname( os.path.realpath(__file__)) + "\UI\MetricsView.ui" loader = QtUiTools.QUiLoader() file = QtCore.QFile(binaryUIPath) file.open(QtCore.QFile.ReadOnly) myWidget = loader.load(file, self.wid) self.authorClassification = AuthorClassification.AuthorClassification() self.getChoice1Classification() self.getChoice2Classification() self.getChoice18Classification() self.getStringSimilaritiesClassification() # Grid layout = QtGui.QVBoxLayout() layout.addWidget(myWidget) self.getAuthorsList() comboBoxes = self.wid.findChildren(QtGui.QComboBox) tableView = self.wid.findChildren(QtGui.QTableWidget, "tableWidget")[0] authorTableView = self.wid.findChildren(QtGui.QTableWidget, "tableWidget_2")[0] for combo in comboBoxes: if "comboBox" in combo.objectName(): combo.insertItems(0, ["1", "5", "10", "15", "50", "100"]) for author in self.authors.keys(): count = tableView.rowCount() tableView.insertRow(count) authorName = QtGui.QTableWidgetItem(author) tableView.setItem(count, 0, authorName) if 'strings' in self.authors[author].keys(): stringSimilarity = QtGui.QTableWidgetItem( str(self.authors[author]["strings"])) tableView.setItem(count, 1, stringSimilarity) if 'choice1' in self.authors[author].keys(): choice1Similarity = QtGui.QTableWidgetItem( str(self.authors[author]["choice1"])) tableView.setItem(count, 2, choice1Similarity) if 'choice2' in self.authors[author].keys(): choice2Similarity = QtGui.QTableWidgetItem( str(self.authors[author]["choice2"])) tableView.setItem(count, 3, choice2Similarity) if 'choice18' in self.authors[author].keys(): choice18Similarity = QtGui.QTableWidgetItem( str(self.authors[author]["choice18"])) tableView.setItem(count, 4, choice18Similarity) sortedAuthorMatches = sorted(self.authorRanking, key=self.authorRanking.get, reverse=True) for author in sortedAuthorMatches: count = authorTableView.rowCount() authorTableView.insertRow(count) authorName = QtGui.QTableWidgetItem(author) authorTableView.setItem(count, 0, authorName) authorSimilarity = QtGui.QTableWidgetItem( str(self.authorRanking[author] * 100)) authorTableView.setItem(count, 1, authorSimilarity) authorTableView.item(count, 1).setBackground( self.returnColor(self.authorRanking[author])) authorTableView.item(count, 0).setBackground( self.returnColor(self.authorRanking[author])) file.close() self.parent.setLayout(layout)
def __init__(self): super(Handheld_camera_shooting, self).__init__() self.setWindowTitle('Handheld camera shooting') self.setMinimumWidth(300) self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) self.setGeometry(1200, 50, 250, 150) self.setModal(False) self.setMaximumWidth(500) self.setMaximumHeight(900) self.cam_aim_aim_name = '' self.cam_aim_cam_name = '' self.cam_aim_cam_grp = '' self.cam_aim_cam_trans = '' self.cam_aim_cam_scale = '' self.cam_aim_cam_rot = '' main_layout = QtGui.QVBoxLayout(self) style_sheet_file = QtCore.QFile( os.path.join(os.path.dirname(__file__), 'stylesheets', 'scheme.qss')) style_sheet_file.open(QtCore.QFile.ReadOnly) self.setStyleSheet(str(style_sheet_file.readAll())) cam_con_move_button = QtGui.QPushButton('Camera Rig') main_layout.addWidget(cam_con_move_button) create_cam_layout = QtGui.QHBoxLayout() self.cam_name_lineedit = QtGui.QLineEdit('camera1') self.cteate_cam_button = QtGui.QPushButton('Create Camera') self.cteate_cam_button.setMinimumWidth(120) self.cteate_cam_button.setObjectName('roundedButton') create_cam_layout.addWidget(self.cam_name_lineedit) create_cam_layout.addWidget(self.cteate_cam_button) # main_layout.addLayout(create_cam_layout) mag_layout = QtGui.QHBoxLayout() frame_layout = QtGui.QHBoxLayout() frame_start_layout = QtGui.QHBoxLayout() frame_end_layout = QtGui.QHBoxLayout() frame_layout.addLayout(frame_start_layout) frame_layout.addLayout(frame_end_layout) main_layout.addLayout(frame_layout) button_layout = QtGui.QHBoxLayout() fre_layout = QtGui.QHBoxLayout() frame_start_label = QtGui.QLabel('Frame Start:') self.frame_start_lineedit = QtGui.QLineEdit('0') frame_start_layout.addWidget(frame_start_label) frame_start_layout.addWidget(self.frame_start_lineedit) frame_end_label = QtGui.QLabel('Frame End:') self.frame_end_lineedit = QtGui.QLineEdit('100') frame_end_layout.addWidget(frame_end_label) frame_end_layout.addWidget(self.frame_end_lineedit) self.mag_label = QtGui.QLabel('Magnitude') self.fre_label = QtGui.QLabel('Frame Step') self.magnitude_line_edit = QtGui.QLineEdit('0.01') self.magnitude_line_edit.setFixedHeight(30) mag_layout.addWidget(self.mag_label) mag_layout.addWidget(self.magnitude_line_edit) self.frequency_line_edit = QtGui.QLineEdit('4') self.frequency_line_edit.setFixedHeight(30) fre_layout.addWidget(self.fre_label) fre_layout.addWidget(self.frequency_line_edit) shake_button = QtGui.QPushButton('Key Rot') shake_button.setFixedHeight(50) trans_button = QtGui.QPushButton('Key Translate') trans_button.setFixedHeight(50) main_layout.addLayout(mag_layout) main_layout.addLayout(fre_layout) ################################################################## check_layout = QtGui.QHBoxLayout() self.rotx_check = QtGui.QCheckBox('X') self.rotx_check.setCheckState(QtCore.Qt.Checked) self.roty_check = QtGui.QCheckBox('Y') self.roty_check.setCheckState(QtCore.Qt.Checked) self.rotz_check = QtGui.QCheckBox('Z') self.rotz_check.setCheckState(QtCore.Qt.Checked) check_layout.addWidget(self.rotx_check) check_layout.addWidget(self.roty_check) check_layout.addWidget(self.rotz_check) main_layout.addLayout(check_layout) button_layout.addWidget(shake_button) button_layout.addWidget(trans_button) main_layout.addLayout(button_layout) shake_button.clicked.connect(self.Cam_shake) trans_button.clicked.connect(self.Cam_shake_tran) self.cteate_cam_button.clicked.connect(self.create_cam) cam_con_move_button.clicked.connect(self.cam_con_move) self.label = QtGui.QLabel("About Qt MessageBox") self.about_button = QtGui.QPushButton('about') main_layout.addWidget(self.about_button) self.about_button.clicked.connect(self.slotAbout)
import os from PySide import QtGui, QtCore import pyregistry as rg import xml.etree.ElementTree as xml import general.ui.pysideuic as pysideuic from cStringIO import StringIO from xml.etree.ElementTree import parse, SubElement PYFILEDIR = os.path.dirname(os.path.abspath(__file__)) uifile = QtCore.QFile("ui/thanks.ui") def loadUiType(uiFile): parsed = xml.parse(uiFile) widget_class = parsed.find('widget').get('class') form_class = parsed.find('class').text with open(uiFile, 'r') as f: o = StringIO() frame = {} pysideuic.compileUi(f, o, indent=0) pyc = compile(o.getvalue(), '<string>', 'exec') exec pyc in frame #Fetch the base_class and form class based on their type in the xml from designer form_class = frame['Ui_%s' % form_class] base_class = eval('QtGui.%s' % widget_class) return form_class, base_class
def __init__(self): self.app = QtGui.QApplication(sys.argv) guiloader = QUiLoader() f = QtCore.QFile('gui/mainwindow.ui') f.open(QtCore.QFile.ReadOnly) self.ui = guiloader.load(f) f.close() self.app.setStyle('Plastique') with open('gui/style.stylesheet', 'r') as (f): self.app.setStyleSheet(f.read()) self.viewerprevioustab = -1 self.timelineprevioustab = -1 self.experiment = config.experiment() self.folderwatcher = watcher.newfilewatcher() self.ui.findChild(QtGui.QAction, 'actionOpen').triggered.connect(self.dialogopen) self.ui.findChild(QtGui.QAction, 'actionTimeline').triggered.connect( self.opentimeline) self.ui.findChild(QtGui.QAction, 'actionAdd').triggered.connect(self.addmode) self.ui.findChild(QtGui.QAction, 'actionSubtract').triggered.connect( self.subtractmode) self.ui.findChild(QtGui.QAction, 'actionAdd_with_coefficient').triggered.connect( self.addwithcoefmode) self.ui.findChild(QtGui.QAction, 'actionSubtract_with_coefficient').triggered.connect( self.subtractwithcoefmode) self.ui.findChild(QtGui.QAction, 'actionDivide').triggered.connect(self.dividemode) self.ui.findChild(QtGui.QAction, 'actionAverage').triggered.connect(self.averagemode) self.ui.findChild(QtGui.QAction, 'actionExport_Image').triggered.connect( self.exportimage) self.ui.findChild(QtGui.QAction, 'actionLog_Intensity').setChecked(True) self.experimentTree = ParameterTree() settingsList = self.ui.findChild(QtGui.QVBoxLayout, 'propertiesBox') settingsList.addWidget(self.experimentTree) self.filetreemodel = QtGui.QFileSystemModel() self.filetree = self.ui.findChild(QtGui.QTreeView, 'treebrowser') self.filetree.setModel(self.filetreemodel) self.filetreepath = '/Volumes' self.treerefresh(self.filetreepath) header = self.filetree.header() self.filetree.setHeaderHidden(True) for i in range(1, 4): header.hideSection(i) filefilter = ['*.tif', '*.edf', '*.fits', '*.nxs', '*.hdf'] self.filetreemodel.setNameFilters(filefilter) self.filetreemodel.setNameFilterDisables(False) self.filetreemodel.setResolveSymlinks(True) self.filetree.expandAll() self.preview = viewer.previewwidget(self.filetreemodel) self.ui.findChild(QtGui.QVBoxLayout, 'smallimageview').addWidget(self.preview) self.libraryview = library.librarylayout(self, '/Volumes') self.ui.findChild(QtGui.QWidget, 'thumbbox').setLayout(self.libraryview) self.openfileslistview = self.ui.findChild(QtGui.QListView, 'openfileslist') self.listmodel = models.openfilesmodel( self.ui.findChild(QtGui.QTabWidget, 'tabWidget')) self.openfileslistview.setModel(self.listmodel) self.ui.findChild(QtGui.QCheckBox, 'filebrowsercheck').stateChanged.connect( self.filebrowserpanetoggle) self.ui.findChild(QtGui.QCheckBox, 'openfilescheck').stateChanged.connect( self.openfilestoggle) self.ui.findChild(QtGui.QCheckBox, 'watchfold').stateChanged.connect( self.watchfoldtoggle) self.ui.findChild(QtGui.QCheckBox, 'experimentfold').stateChanged.connect( self.experimentfoldtoggle) integrationwidget = pg.PlotWidget() self.integration = integrationwidget.getPlotItem() self.integration.setLabel('bottom', u'q (\u212b\u207b\xb9)', '') self.qLine = pg.InfiniteLine(angle=90, movable=False, pen=pg.mkPen('#FFA500')) self.qLine.setVisible(False) self.integration.addItem(self.qLine) self.ui.findChild(QtGui.QVBoxLayout, 'plotholder').addWidget(integrationwidget) timelineplot = pg.PlotWidget() self.timeline = timelineplot.getPlotItem() self.timeline.showAxis('left', False) self.timeline.showAxis('bottom', False) self.timeline.showAxis('top', True) self.timeline.showGrid(x=True) self.timeline.getViewBox().setMouseEnabled(x=False, y=True) self.ui.findChild(QtGui.QVBoxLayout, 'timeline').addWidget(timelineplot) menu = self.timeline.getViewBox().menu operationcombo = QtGui.QComboBox() operationcombo.setObjectName('operationcombo') operationcombo.addItems([ 'Chi Squared', 'Abs. difference', 'Norm. Abs. difference', 'Sum intensity', 'Norm. Abs. Diff. derivative' ]) operationcombo.currentIndexChanged.connect( self.changetimelineoperation) opwidgetaction = QtGui.QWidgetAction(menu) opwidgetaction.setDefaultWidget(operationcombo) menu.addAction(opwidgetaction) self.timelinetoolbar = toolbar.difftoolbar() self.timelinetoolbar.connecttriggers( self.calibrate, self.centerfind, self.refinecenter, self.redrawcurrent, self.redrawcurrent, self.redrawcurrent, self.linecut, self.vertcut, self.horzcut, self.redrawcurrent, self.redrawcurrent, self.redrawcurrent, self.roi) self.ui.timelinebox.insertWidget(0, self.timelinetoolbar) self.timelinetoolbar.actionHorizontal_Cut.setEnabled(False) self.timelinetoolbar.actionVertical_Cut.setEnabled(False) self.timelinetoolbar.actionLine_Cut.setEnabled(False) self.difftoolbar = toolbar.difftoolbar() self.difftoolbar.connecttriggers( self.calibrate, self.centerfind, self.refinecenter, self.redrawcurrent, self.redrawcurrent, self.redrawcurrent, self.linecut, self.vertcut, self.horzcut, self.redrawcurrent, self.redrawcurrent, self.redrawcurrent, self.roi) self.ui.diffbox.insertWidget(0, self.difftoolbar) self.booltoolbar = QtGui.QToolBar() self.booltoolbar.addAction( self.ui.findChild(QtGui.QAction, 'actionTimeline')) self.booltoolbar.addAction( self.ui.findChild(QtGui.QAction, 'actionAdd')) self.booltoolbar.addAction( self.ui.findChild(QtGui.QAction, 'actionSubtract')) self.booltoolbar.addAction( self.ui.findChild(QtGui.QAction, 'actionAdd_with_coefficient')) self.booltoolbar.addAction( self.ui.findChild(QtGui.QAction, 'actionSubtract_with_coefficient')) self.booltoolbar.addAction( self.ui.findChild(QtGui.QAction, 'actionDivide')) self.booltoolbar.addAction( self.ui.findChild(QtGui.QAction, 'actionAverage')) self.booltoolbar.setIconSize(QtCore.QSize(32, 32)) self.ui.findChild(QtGui.QVBoxLayout, 'leftpanelayout').addWidget(self.booltoolbar) self.ui.findChild(QtGui.QSplitter, 'splitter').setSizes([500, 1]) self.ui.findChild(QtGui.QSplitter, 'splitter_3').setSizes([200, 1, 200]) self.ui.findChild(QtGui.QSplitter, 'splitter_2').setSizes([150, 1]) self.ui.findChild(QtGui.QSplitter, 'splitter_4').setSizes([500, 1]) self.ui.statusbar.showMessage('Ready...') self.app.processEvents() self.ui.findChild(QtGui.QTabWidget, 'tabWidget').tabCloseRequested.connect( self.tabCloseRequested) self.ui.findChild(QtGui.QTabWidget, 'tabWidget').currentChanged.connect( self.currentchanged) self.ui.findChild(QtGui.QTabWidget, 'timelinetabwidget').currentChanged.connect( self.currentchangedtimeline) self.ui.findChild(QtGui.QTabWidget, 'timelinetabwidget').tabCloseRequested.connect( self.timelinetabCloseRequested) self.filetree.clicked.connect(self.preview.loaditem) self.filetree.doubleClicked.connect(self.itemopen) self.openfileslistview.doubleClicked.connect(self.switchtotab) self.ui.findChild(QtGui.QDialogButtonBox, 'watchbuttons').button( QtGui.QDialogButtonBox.Open).clicked.connect(self.openwatchfolder) self.ui.findChild(QtGui.QDialogButtonBox, 'watchbuttons').button( QtGui.QDialogButtonBox.Reset).clicked.connect( self.resetwatchfolder) self.folderwatcher.newFilesDetected.connect(self.newfilesdetected) self.ui.librarybutton.clicked.connect(self.showlibrary) self.ui.viewerbutton.clicked.connect(self.showviewer) self.ui.timelinebutton.clicked.connect(self.showtimeline) self.rmcpugin = rmc.gui(self.ui) self.bindexperiment() self.ui.show() print 'BLAH!' sys.exit(self.app.exec_())
def __init__(self, app): QtCore.QObject.__init__(self, app) 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.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 edit_base(self, base=None): """ Creates the dialog box for base creation. If base isn't None, prefill with the info contained :param base: an Acd.Workbase object :return: """ if not self.menu.editButton.isEnabled(): return edit_base_box = QtUiTools.QUiLoader().load( QtCore.QFile("H3/GUI/QtDesigns/EditBaseBox.ui"), self.gui.root_window) edit_base_box.countryComboBox.setModel(self.countries_model) edit_base_box.timeZoneComboBox.setModel(self.timezones_model) edit_base_box.parentComboBox.setModel(self.parents_model) edit_base_box.countryComboBox.highlighted[str].connect( self.update_timezones) # Receiving a QModelIndex from the "activated" signal if not base or type(base) != Acd.WorkBase: base = self.selected_base edit_base_box.baseCodeLineEdit.setText(base.identifier) parent_base = H3Core.get_from_primary_key(Acd.WorkBase, base.parent) if parent_base: edit_base_box.parentComboBox.setCurrentIndex( edit_base_box.parentComboBox.findText( parent_base.identifier, QtCore.Qt.MatchStartsWith)) edit_base_box.fullNameLineEdit.setText(base.full_name) edit_base_box.openingDateDateEdit.setDate(base.opened_date) edit_base_box.countryComboBox.setCurrentIndex( edit_base_box.countryComboBox.findText(base.country, QtCore.Qt.MatchStartsWith)) self.update_timezones(base.country) edit_base_box.timeZoneComboBox.setCurrentIndex( edit_base_box.timeZoneComboBox.findData(base.time_zone, 33, QtCore.Qt.MatchExactly)) if edit_base_box.exec_() == QtGui.QDialog.Accepted: base.parent = edit_base_box.parentComboBox.itemData( edit_base_box.parentComboBox.currentIndex(), 33).code or None base.identifier = edit_base_box.baseCodeLineEdit.text() base.full_name = edit_base_box.fullNameLineEdit.text() base.opened_date = edit_base_box.openingDateDateEdit.date( ).toPython() base.country = edit_base_box.countryComboBox.itemData( edit_base_box.countryComboBox.currentIndex(), 33)[1] base.time_zone = edit_base_box.timeZoneComboBox.itemData( edit_base_box.timeZoneComboBox.currentIndex(), 33) if H3Core.update_base(base) == "OK": self.refresh_tree(H3Core.current_job_contract.work_base) else: message_box = QtGui.QMessageBox( QtGui.QMessageBox.Warning, _("Base not modified"), _("H3 could not modify this base. Check all data is valid" ), QtGui.QMessageBox.Ok) message_box.setWindowIcon(QtGui.QIcon(":/images/H3.png")) message_box.exec_()
def create_base(self, base=None): """ Creates the dialog box for base creation. If base isn't None, prefill with the info contained :param base: an Acd.Workbase object :return: """ # TODO : Make core check you have the proper rights create_base_box = QtUiTools.QUiLoader().load( QtCore.QFile("H3/GUI/QtDesigns/CreateBaseBox.ui"), self.gui.root_window) create_base_box.countryComboBox.setModel(self.countries_model) create_base_box.timeZoneComboBox.setModel(self.timezones_model) create_base_box.parentComboBox.setModel(self.parents_model) create_base_box.countryComboBox.highlighted[str].connect( self.update_timezones) if base: create_base_box.baseCodeLineEdit.setText(base.identifier) parent_base = H3Core.get_from_primary_key(Acd.WorkBase, base.parent) if parent_base: create_base_box.parentComboBox.setCurrentIndex( create_base_box.parentComboBox.findText( parent_base.identifier, QtCore.Qt.MatchStartsWith)) create_base_box.fullNameLineEdit.setText(base.full_name) create_base_box.openingDateDateEdit.setDate(base.opened_date) create_base_box.countryComboBox.setCurrentIndex( create_base_box.countryComboBox.findText( base.country, QtCore.Qt.MatchStartsWith)) self.update_timezones(base.country) create_base_box.timeZoneComboBox.setCurrentIndex( create_base_box.timeZoneComboBox.findData( base.time_zone, 33, QtCore.Qt.MatchExactly)) else: create_base_box.parentComboBox.setCurrentIndex( create_base_box.parentComboBox.findText( self.selected_base.identifier, QtCore.Qt.MatchStartsWith)) create_base_box.openingDateDateEdit.setDate(datetime.date.today()) create_base_box.countryComboBox.setCurrentIndex( create_base_box.countryComboBox.findText( self.selected_base.country, QtCore.Qt.MatchStartsWith)) self.update_timezones(self.selected_base.country) if create_base_box.exec_() == QtGui.QDialog.Accepted: # noinspection PyArgumentList new_base = Acd.WorkBase( base='BASE-1', period='PERMANENT', identifier=create_base_box.baseCodeLineEdit.text(), # Next line "or None" makes a parent-less base creation fail - unnecessary parent=create_base_box.parentComboBox.itemData( create_base_box.parentComboBox.currentIndex(), 33).code, full_name=create_base_box.fullNameLineEdit.text(), opened_date=create_base_box.openingDateDateEdit.date(). toPython(), country=create_base_box.countryComboBox.itemData( create_base_box.countryComboBox.currentIndex(), 33)[1], time_zone=create_base_box.timeZoneComboBox.itemData( create_base_box.timeZoneComboBox.currentIndex(), 33)) if H3Core.create_base(new_base) == "OK": self.refresh_tree(H3Core.current_job_contract.work_base) else: message_box = QtGui.QMessageBox( QtGui.QMessageBox.Warning, _("Base not created"), _("H3 could not create this base. Check all data is valid" ), QtGui.QMessageBox.Ok) message_box.setWindowIcon(QtGui.QIcon(":/images/H3.png")) message_box.exec_()
def init_ui(self): f = QtCore.QFile('F:\\GitHub\\AssetBrowser\\AssetBrowserUI2.ui') f.open(QtCore.QFile.ReadOnly) loader = QtUiTools.QUiLoader() self.ui = loader.load(f, parentWidget=None) f.close()
def launch_notification(self, reminder_id): due = note = None try: with session_scope() as session: reminder = session.query(Reminder).get(int(reminder_id)) due = reminder.due note = reminder.note reminder.complete = True except Exception as uexc: logger.error(str(uexc)) QtGui.QMessageBox(self, 'Unexpected exception', 'Could not mark due reminder as complete') return # Get local datetime for output to user and format note as html local_due = dt2str(utcstr2local(due, self.time_zone, date_format='%Y-%m-%d %H:%M'), date_format='%d %b %I:%M%p') htmlcontent = '<p>%s</p>' % note # QApplication.instance().beep() # if QtGui.QSound.isAvailable(): # # Seems I would have to recompile with NAS support, but # # what does that mean for python when pyside was pip installed?? # QtGui.QSound.play("media/alarm_beep.wav") media = Phonon.MediaObject() audio = Phonon.AudioOutput(Phonon.MusicCategory) Phonon.createPath(media, audio) # alarm_file = os.path.join(os.getcwd(), 'media/alarm_beep.wav') alarm_file = resource_path('alarm_beep.wav') logger.debug('Trying to open alarm file...%s' % alarm_file) f = QtCore.QFile(alarm_file) if f.exists(): source = Phonon.MediaSource(alarm_file) if source.type() != -1: # -1 stands for invalid file media.setCurrentSource(source) media.play() else: logger.debug('Alert media missing: %s' % alarm_file) # Systray notification self.tray_icon.showMessage(unicode('Reminder due at %s' % local_due), smart_truncate(note, length=100), QtGui.QSystemTrayIcon.Information, 5000) # Dialog notification self.show() dlg = NotificationDialog() dlg.notificationTextBrowser.setHtml(htmlcontent) dlg.dtLabel.setText(local_due) dlg.setWindowTitle(unicode('Due at %s' % local_due)) # Change std buttons to "Reschedule" and "Mark Complete". # Resched will set complete=False and launch the edit reminder with # time selected. "Mark Complete" does nothing, since we already # marked complete to prevent further popups dlg.notificationButtonBox.button( QtGui.QDialogButtonBox.Ok).setText('Mark Complete') dlg.notificationButtonBox.button( QtGui.QDialogButtonBox.Cancel).setText('Reschedule') if dlg.exec_(): logger.debug( 'User wants to close dlg and keep the reminder as completed') else: # Launch edit reminder logger.debug('User wants to reschedule') self.addedit_rem_action_triggered(reminder_id=reminder_id) # Refresh table to account for this reminder completion self.refresh_table()
def loadUiWidget(self, uifilename, parent=None): loader = QtUiTools.QUiLoader() uifile = QtCore.QFile(uifilename) uifile.open(QtCore.QFile.ReadOnly) self.ui = loader.load(uifile, parent) uifile.close()
def lemon(conf = None): base.check_install('pyside') if not conf: if base.conf.folder == 'problem': raise Exception('Can\'t dump a single problem to lemon, try to dump a day or a contest.') base.remkdir('lemon') if base.conf.folder == 'day': lemon(base.conf) else: for day in base.days(): os.makedirs(base.pjoin('lemon', day.route)) lemon(day) return log.info(u'导出lemon工程:%s' % conf.route) os.makedirs(base.pjoin('lemon', conf.route, 'data')) os.makedirs(base.pjoin('lemon', conf.route, 'source')) jzp_magic = 0x20111127 zlib_magic = 0x185E import zlib from PySide import QtCore obuff = QtCore.QByteArray() ost = QtCore.QDataStream(obuff, QtCore.QIODevice.WriteOnly) ost.writeQString(conf['name']) probs = list(conf.probs()) ost.writeInt32(len(probs)) for prob in probs: log.info(u'导出lemon题目:%s' % prob.route) ost.writeQString(base.tr(prob['title'])) ost.writeQString(prob['name']) ost.writeQString(prob['name'] + '.in') ost.writeQString(prob['name'] + '.out') ost.writeBool(False) ost.writeBool(False) ost.writeInt32(1 if prob['type'] == 'output' else 0) ost.writeInt32(1) # Judge Type TODO: What if there is spj (code = 4) ost.writeQString('--ignore-space-change --text --brief') ost.writeInt32(3) # real precision (float number error bound) ost.writeQString('') # spj route TODO: What if there is spj ost.writeInt32(len([i for i in prob.get('compile', {}) if i in {'cpp', 'c', 'pas'}])) for key, val in prob.get('compile', {}).items(): try: ost.writeQString({ 'cpp' : 'g++', 'c' : 'gcc', 'pas' : 'fpc' }[key]) ost.writeQString(val) except: pass ost.writeQString('out') if prob.packed: ost.writeInt32(len(prob['data'])) for datum in prob['data']: ost.writeInt32(datum['score']) ost.writeInt32(datum.get('time limit', prob.get('time limit', 0)) * 1000) ost.writeInt32(base.Memory(datum.get('memory limit', prob.get('memory limit', '0 B'))).MB) tc = datum['cases'] ost.writeInt32(len(tc)) for c in tc: ost.writeQString(base.pjoin(prob['name'], str(c) + '.in')) ost.writeInt32(len(tc)) for c in tc: ost.writeQString(base.pjoin(prob['name'], str(c) + '.ans')) else: score = (100. / len(prob.test_cases) if len(prob.test_cases) > 0 else 0.) ost.writeInt32(len(prob.test_cases)) for c in prob.test_cases: ost.writeInt32(score) ost.writeInt32(prob['time limit'] * 1000) ost.writeInt32(prob.memory_limit().MB) ost.writeInt32(1) ost.writeQString(base.pjoin(prob['name'], str(c) + '.in')) ost.writeInt32(1) ost.writeQString(base.pjoin(prob['name'], str(c) + '.ans')) sp = list(prob.route.split('/')) target = ['lemon'] + sp[:-1] + ['data', sp[-1]] shutil.copytree(base.pjoin(prob.path, 'data'), base.pjoin(*target)) compressed = QtCore.QByteArray(zlib.compress(str(obuff))) obuff = QtCore.QByteArray() ost = QtCore.QDataStream(obuff, QtCore.QIODevice.WriteOnly) ost.writeUInt32(zlib_magic) ost.writeRawData(str(compressed)) file_ = QtCore.QFile(base.pjoin('lemon', conf.route, conf['name'] + '.cdf')) file_.open(QtCore.QIODevice.WriteOnly) ofs = QtCore.QDataStream(file_) ofs.writeUInt32(jzp_magic) ofs.writeUInt16(QtCore.qChecksum(str(obuff), len(obuff))) ofs.writeUInt32(len(obuff)) ofs.writeRawData(str(obuff)) file_.close() base.run_r(base.unix2dos, base.pjoin('lemon', conf.route, 'data')) if base.do_zip: import zipfile with zipfile.ZipFile(base.pjoin('lemon', conf.route) + '.zip', 'w') as z: base.run_r(lambda path : z.write(path), base.pjoin('lemon', conf.route)) log.warning(u'目前SPJ的支持暂时还没有实现,有需要请手工配置。') log.warning(u'目前lemon的编译选项是写在注册表里的,暂时没有实现该功能,请手工配置。')
def downloadFile(self): url = QtCore.QUrl(self.urlLineEdit.text()) fileInfo = QtCore.QFileInfo(url.path()) fileName = fileInfo.fileName() if not fileName: fileName = 'index.html' if QtCore.QFile.exists(fileName): ret = QtGui.QMessageBox.question( self, "HTTP", "There already exists a file called %s in the current " "directory." % fileName, QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Cancel) if ret == QtGui.QMessageBox.Cancel: return QtCore.QFile.remove(fileName) self.outFile = QtCore.QFile(fileName) if not self.outFile.open(QtCore.QIODevice.WriteOnly): QtGui.QMessageBox.information( self, "HTTP", "Unable to save the file %s: %s." % (fileName, self.outFile.errorString())) self.outFile = None return if url.scheme().lower() == 'https': mode = QtNetwork.QHttp.ConnectionModeHttps else: mode = QtNetwork.QHttp.ConnectionModeHttp port = url.port() if port == -1: port = 0 self.http.setHost(url.host(), mode, port) if url.userName(): self.http.setUser(url.userName(), url.password()) self.httpRequestAborted = False path = QtCore.QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/") if path: try: # Python v3. path = str(path, encoding='utf-8') except TypeError: # Python v2. path = str(path) else: path = '/' self.httpGetId = self.http.get(path, self.outFile) self.progressDialog.setWindowTitle("HTTP") self.progressDialog.setLabelText("Downloading %s." % fileName) self.downloadButton.setEnabled(False)
import sys from PySide import QtCore, QtGui, QtUiTools #import QtCore def on_click(): print("clicketd") if __name__ == "__main__": app = QtGui.QApplication(sys.argv) loader = QtUiTools.QUiLoader() uifile = QtCore.QFile("mainwindow.ui") uifile.open(QtCore.QFile.ReadOnly) MainWindow = loader.load(uifile, None) uifile.close() MainWindow.connect(MainWindow.button1, QtCore.SIGNAL("clicked()"), on_click) MainWindow.show() sys.exit(app.exec_())
import os import pyregistry as rg from PySide import QtGui, QtCore import xml.etree.ElementTree as xml from xml.etree.ElementTree import parse, SubElement import general.ui.pysideuic as pysideuic from cStringIO import StringIO import client import shutil PYFILEDIR = os.path.dirname(os.path.abspath(__file__)) uifile = QtCore.QFile("ui/install.ui") def loadUiType(uiFile): parsed = xml.parse(uiFile) widget_class = parsed.find('widget').get('class') form_class = parsed.find('class').text with open(uiFile, 'r') as f: o = StringIO() frame = {} pysideuic.compileUi(f, o, indent=0) pyc = compile(o.getvalue(), '<string>', 'exec') exec pyc in frame #Fetch the base_class and form class based on their type in the xml from designer form_class = frame['Ui_%s' % form_class]
def loadQTextStream(self): error = None fh = None try: fh = QtCore.QFile(self.__fname) if not fh.open(QtCore.QIODevice.ReadOnly): raise IOError(fh.errorString()) stream = QtCore.QTextStream(fh) stream.setCodec(CODEC) self.clear(False) lino = 0 while not stream.atEnd(): title = year = minutes = acquired = notes = None line = stream.readLine() lino += 1 if not line.startswith("{{MOVIE}}"): raise ValueError("no movie record found") else: title = line[len("{{MOVIE}}"):].strip() if stream.atEnd(): raise ValueError("premature end of file") line = stream.readLine() lino += 1 parts = line.split(" ") if len(parts) != 3: raise ValueError("invalid numeric data") year = int(parts[0]) minutes = int(parts[1]) ymd = parts[2].split("-") if len(ymd) != 3: raise ValueError("invalid acquired date") acquired = QtCore.QDate(int(ymd[0]), int(ymd[1]), int(ymd[2])) if stream.atEnd(): raise ValueError("premature end of file") line = stream.readLine() lino += 1 if line != "{NOTES}": raise ValueError("notes expected") notes = "" while not stream.atEnd(): line = stream.readLine() lino += 1 if line == "{{ENDMOVIE}}": if (title is None or year is None or minutes is None or acquired is None or notes is None): raise ValueError("incomplete record") self.add( Movie(title, year, minutes, acquired, notes.strip())) break else: notes += line + "\n" else: raise ValueError("missing endmovie marker") except (IOError, OSError, ValueError) as e: error = "Failed to load qt text: {} on line {}".format(e, lino) finally: if fh is not None: fh.close() if error is not None: return False, error self.__dirty = False return True, "Loaded {} movie records from {}".format( len(self.__movies), QtCore.QFileInfo(self.__fname).fileName())
def __init__(self): ui_loader = QtUiTools.QUiLoader() print os.path.join(__file__, "scanning_confocal_mcl_ni.ui") ui_file = QtCore.QFile("scanning_confocal_mcl_ni.ui") ui_file.open(QtCore.QFile.ReadOnly) self.ui = ui_loader.load(ui_file) ui_file.close() self.HARDWARE_DEBUG = HARDWARE_DEBUG self.fig2d = Figure() self.ax2d = self.fig2d.add_subplot(111) self.ax2d.plot([0, 1]) self.canvas2d = FigureCanvas(self.fig2d) self.ui.plot2D_verticalLayout.addWidget(self.canvas2d) self.navtoolbar_plot2d = NavigationToolbar2(self.canvas2d, self.ui) self.ui.plot2D_verticalLayout.addWidget(self.navtoolbar_plot2d) self.fig_opt = Figure() self.ax_opt = self.fig_opt.add_subplot(111) self.canvas_opt = FigureCanvas(self.fig_opt) self.ui.plot_optimize_verticalLayout.addWidget(self.canvas_opt) self.navtoolbar_plot_opt = NavigationToolbar2(self.canvas_opt, self.ui) self.ui.plot_optimize_verticalLayout.addWidget( self.navtoolbar_plot_opt) self.optimize_history = np.zeros(OPTIMIZE_HISTORY_LEN, dtype=np.float) self.optimize_ii = 0 self.optimize_line, = self.ax_opt.plot(self.optimize_history) self.optimize_current_pos = self.ax_opt.axvline(self.optimize_ii, color='r') ##################### hardware ######################################### self.scanning = False ######## MCL NanoDrive Stage ########################################### self.nanodrive = MCLNanoDrive(debug=self.HARDWARE_DEBUG) try: self.hmax = self.nanodrive.cal[HAXIS_ID] self.vmax = self.nanodrive.cal[VAXIS_ID] self.ui.maxdim_label.setText("%s - %s scan. Max: %g x %g um" % (HAXIS, VAXIS, self.hmax, self.vmax)) except Exception as e: print e self.ui.maxdim_label.setText("max: ? x ? um") # Logged Quantities self.x_position = LoggedQuantity(name='x_position', dtype=np.float) self.y_position = LoggedQuantity(name='y_position', dtype=np.float) self.z_position = LoggedQuantity(name='z_position', dtype=np.float) #self.x_position.updated_value.connect(self.ui.cx_lcdNumber.display) self.x_position.updated_value.connect( self.ui.cx_doubleSpinBox.setValue) self.ui.x_set_lineEdit.returnPressed.connect( self.x_position.update_value) #self.y_position.updated_value.connect(self.ui.cy_lcdNumber.display) self.y_position.updated_value.connect( self.ui.cy_doubleSpinBox.setValue) self.ui.y_set_lineEdit.returnPressed.connect( self.y_position.update_value) #self.z_position.updated_value.connect(self.ui.cz_lcdNumber.display) self.z_position.updated_value.connect( self.ui.cz_doubleSpinBox.setValue) self.ui.z_set_lineEdit.returnPressed.connect( self.z_position.update_value) self.x_position.hardware_set_func = lambda x: self.nanodrive.set_pos_ax( x, MCL_AXIS_ID["X"]) self.y_position.hardware_set_func = lambda y: self.nanodrive.set_pos_ax( y, MCL_AXIS_ID["Y"]) self.z_position.hardware_set_func = lambda z: self.nanodrive.set_pos_ax( z, MCL_AXIS_ID["Z"]) ####### NI (apd) counter readout ################################## self.ni_counter = NI_FreqCounter(debug=self.HARDWARE_DEBUG) self.apd_count_rate = LoggedQuantity(name='apd_count_rate', dtype=np.float, fmt="%e") self.apd_count_rate.updated_text_value.connect( self.ui.apd_counter_output_lineEdit.setText) ######################################################################## self.read_stage_position() self.read_ni_countrate() self.update_display() # update figure self.ax2d.set_xlim(0, self.hmax) self.ax2d.set_ylim(0, self.vmax) # events self.ui.scan_start_pushButton.clicked.connect(self.on_scan_start) self.ui.scan_stop_pushButton.clicked.connect(self.on_scan_stop) self.ui.fast_update_checkBox.stateChanged.connect( self.on_fast_timer_checkbox) self.ui.clearfig_pushButton.clicked.connect(self.on_clearfig) ### timers self.slow_display_timer = QtCore.QTimer(self.ui) self.slow_display_timer.timeout.connect(self.on_slow_display_timer) self.slow_display_timer.start(TIMER_MS) self.fast_timer = QtCore.QTimer(self.ui) self.fast_timer.timeout.connect(self.on_fast_timer) self.display_update_when_scanning_timer = QtCore.QTimer(self.ui) self.display_update_when_scanning_timer.timeout.connect( self.on_display_update_when_scanning_timer)
from PySide.QtCore import Qt # user defined import globvar from models.ProgModel import ProgModel from models.VideosModel import VideosModel from models.ConfigModel import ConfigModel from views.mainwindow import Ui_MainWindow from controller.VideosController import * from controller.ConfigController import * VID_READY = 'ready' VID_PROCESSING = 'processing' VID_DONE = 'done' VID_ERR = 'err' form_class = QtCore.QFile(os.path.join("views", "mainwindow.ui")) class MainWindowClass(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self._x264_location = os.path.join("tools", "x264", "x264.exe") self._x264_64_location = os.path.join("tools", "x264", "x264_64.exe") self._mp4box_location = os.path.join("tools", "mp4box", "mp4box.exe") self._mkvmerge_location = os.path.join("tools", "mkvmerge", "mkvmerge.exe") self._mkvextract_location = os.path.join("tools", "mkvmerge", "mkvextract.exe") self._avisynth_location = '' self.isWindowFullScreen = False
parents[-1].child(parents[-1].childCount() - 1)) indentations.append(position) else: while position < indentations[-1] and len(parents) > 0: parents.pop() indentations.pop() # Append a new item to the current parent's list of children. parents[-1].appendChild(TreeItem(columnData, parents[-1])) number += 1 if __name__ == '__main__': import sys app = QtGui.QApplication(sys.argv) f = QtCore.QFile(':/default.txt') f.open(QtCore.QIODevice.ReadOnly) model = TreeModel(str(f.readAll())) f.close() view = QtGui.QTreeView() view.setModel(model) view.setWindowTitle("Simple Tree Model") view.show() sys.exit(app.exec_())
def accept(self): className = self.field('className') baseClass = self.field('baseClass') macroName = self.field('macroName') baseInclude = self.field('baseInclude') outputDir = self.field('outputDir') header = self.field('header') implementation = self.field('implementation') block = '' if self.field('comment'): block += '/*\n' block += ' ' + header + '\n' block += '*/\n' block += '\n' if self.field('protect'): block += '#ifndef ' + macroName + '\n' block += '#define ' + macroName + '\n' block += '\n' if self.field('includeBase'): block += '#include ' + baseInclude + '\n' block += '\n' block += 'class ' + className if baseClass: block += ' : public ' + baseClass block += '\n' block += '{\n' if self.field('qobjectMacro'): block += ' Q_OBJECT\n' block += '\n' block += 'public:\n' if self.field('qobjectCtor'): block += ' ' + className + '(QObject *parent = 0);\n' elif self.field('qwidgetCtor'): block += ' ' + className + '(QWidget *parent = 0);\n' elif self.field('defaultCtor'): block += ' ' + className + '();\n' if self.field('copyCtor'): block += ' ' + className + '(const ' + className + ' &other);\n' block += '\n' block += ' ' + className + ' &operator=' + '(const ' + className + ' &other);\n' block += '};\n' if self.field('protect'): block += '\n' block += '#endif\n' headerFile = QtCore.QFile(outputDir + '/' + header) if not headerFile.open(QtCore.QFile.WriteOnly | QtCore.QFile.Text): QtGui.QMessageBox.warning( None, "Class Wizard", "Cannot write file %s:\n%s" % (headerFile.fileName(), headerFile.errorString())) return headerFile.write(str(block)) block = '' if self.field('comment'): block += '/*\n' block += ' ' + implementation + '\n' block += '*/\n' block += '\n' block += '#include "' + header + '"\n' block += '\n' if self.field('qobjectCtor'): block += className + '::' + className + '(QObject *parent)\n' block += ' : ' + baseClass + '(parent)\n' block += '{\n' block += '}\n' elif self.field('qwidgetCtor'): block += className + '::' + className + '(QWidget *parent)\n' block += ' : ' + baseClass + '(parent)\n' block += '{\n' block += '}\n' elif self.field('defaultCtor'): block += className + '::' + className + '()\n' block += '{\n' block += ' // missing code\n' block += '}\n' if self.field('copyCtor'): block += '\n' block += className + '::' + className + '(const ' + className + ' &other)\n' block += '{\n' block += ' *this = other;\n' block += '}\n' block += '\n' block += className + ' &' + className + '::operator=(const ' + className + ' &other)\n' block += '{\n' if baseClass: block += ' ' + baseClass + '::operator=(other);\n' block += ' // missing code\n' block += ' return *this;\n' block += '}\n' implementationFile = QtCore.QFile(outputDir + '/' + implementation) if not implementationFile.open(QtCore.QFile.WriteOnly | QtCore.QFile.Text): QtGui.QMessageBox.warning( None, "Class Wizard", "Cannot write file %s:\n%s" % (implementationFile.fileName(), implementationFile.errorString())) return implementationFile.write(str(block)) super(ClassWizard, self).accept()
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 setupUI(self): #self.app.setWindowIcon(QtGui.QIcon('../icons/favicon.png')) ui_filename = self.ui_filename ui_loader = QtUiTools.QUiLoader() ui_file = QtCore.QFile(ui_filename) ui_file.open(QtCore.QFile.ReadOnly); self.ui = ui_loader.load(ui_file) ui_file.close() self.ui.setWindowTitle('STEM Focal Series') self.ui.inTim.setText(str(self.dweTim)) self.ui.inBin.setText(str(self.bin)) self.ui.inOutDir.setText(os.getcwd()) self.ui.inFilInd.setText(str(self.intIndex)) self.ui.inUsrOutDir.setText(str(self.usrDir)) self.ui.inSamInf.setText(str(self.samInf)) self.ui.inResNam.setText(str(self.usrNam)) self.ui.lblSlider.setText('Image 1 of 11') self.ui.inMaxBin.setText("2048") self.ui.inFilPre.setText("STEMSeries $time $params") self.ui.inNum.setText("11") self.ui.inTim.setText("12") self.ui.inSte.setText("2") self.ui.inMax.setText("10") self.ui.inMin.setText("-10") self.ui.inSetTim.setText("2") self.ui.inNumRep.setText("1") self.ui.lblStatus.setText('Idle...') self.ui.viewSlider.setMinimum(1) self.ui.viewSlider.setMaximum(11) self.ui.viewSlider.setTickInterval(1) self.ui.viewSlider.setSingleStep(1) self.ui.viewSlider.setTickPosition(QtGui.QSlider.TickPosition(3)) self.ui.viewSlider.valueChanged.connect(self.sliderMoved) self.ui.progressBar.setVisible(False) self.ui.progressBar.setMinimum(1) self.ui.progressBar.setMaximum(11) self.ui.inMin.setValidator(QtGui.QDoubleValidator()) self.ui.inSte.setValidator(QtGui.QDoubleValidator()) self.ui.inBin.setValidator(QtGui.QIntValidator()) self.ui.inMin.textChanged.connect(self.checkDef) self.ui.inSte.textChanged.connect(self.checkDef) self.ui.connect(self.ui.inOutDir, QtCore.SIGNAL ('textChanged()'), self.checkDir()) self.ui.inOutDir.textChanged.connect(self.checkDir) self.ui.inBin.textChanged.connect(self.checkBin) self.ui.actionSTEM.triggered.connect(self.STEMMODE) self.ui.actionTEM.triggered.connect(self.TEMMODE) self.ui.actionFocal.triggered.connect(self.FOCMODE) self.ui.actionTilt.triggered.connect(self.TILTMODE) self.ui.actionSTEM.setCheckable(True) self.ui.actionTEM.setCheckable(True) self.ui.actionFocal.setCheckable(True) self.ui.actionTilt.setCheckable(True) self.ui.actionSTEM.setChecked(True) self.ui.actionFocal.setChecked(True) self.ui.inSte.returnPressed.connect(self.updateCount) self.ui.inMin.returnPressed.connect(self.updateCount) self.ui.inMax.returnPressed.connect(self.updateCount) self.ui.inNum.returnPressed.connect(self.updateStep) self.ui.usrButton.released.connect(self._saveUserSettings) self.ui.acqBtn.released.connect(self.onAcquire) self.ui.savBtn.released.connect(self.onSave) self.ui.aboBtn.released.connect(self.onAbort) self.ui.broBtn.released.connect(self.onBrowse) self.ui.usrBroBtn.released.connect(self.onBrowse) self.scene = QtGui.QGraphicsScene() self.ui.graphicsView.setScene(self.scene) self.ui.graphicsView.fitInView(self.scene.itemsBoundingRect(),QtCore.Qt.KeepAspectRatio) #self.app.aboutToQuit.connect(self._saveAcqSettings()) self.hotkeys()
def readInfo(self, resource, dir_): categoriesFile = QtCore.QFile(resource) document = QtXml.QDomDocument() document.setContent(categoriesFile) documentElement = document.documentElement() categoryNodes = documentElement.elementsByTagName("category") self.categories['[main]'] = {} self.categories['[main]']['examples'] = [] self.categories['[main]']['color'] = QtGui.QColor("#f0f0f0") self.readCategoryDescription(dir_, '[main]') self.qtLogo.load( self.imagesDir.absoluteFilePath(":/images/qt4-logo.png")) self.rbLogo.load( self.imagesDir.absoluteFilePath(":/images/rb-logo.png")) for i in range(categoryNodes.length()): elem = categoryNodes.item(i).toElement() categoryName = QtCore.QString(elem.attribute("name")) categoryDirName = QtCore.QString(elem.attribute("dirname")) categoryDocName = QtCore.QString(elem.attribute("docname")) categoryColor = QtGui.QColor(elem.attribute("color", "#f0f0f0")) categoryDir = QtCore.QDir(dir_) if categoryDir.cd(categoryDirName): self.categories[categoryName] = {} self.readCategoryDescription(categoryDir, categoryName) self.categories[categoryName]['examples'] = [] exampleNodes = elem.elementsByTagName("example") self.maximumLabels = max(self.maximumLabels, exampleNodes.length()) # Only add those examples we can find. for j in range(exampleNodes.length()): exampleDir = QtCore.QDir(categoryDir) exampleNode = exampleNodes.item(j) element = exampleNode.toElement() exampleName = element.attribute("name") exampleFileName = element.attribute("filename") uniqueName = categoryName + "-" + exampleName self.examples[uniqueName] = {} if not categoryDocName.isEmpty(): docName = categoryDocName + "-" + exampleFileName + ".html" else: docName = categoryDirName + "-" + exampleFileName + ".html" self.examples[uniqueName]['name'] = exampleName self.examples[uniqueName]['document path'] = "" self.findDescriptionAndImages(uniqueName, docName) self.examples[uniqueName][ 'changedirectory'] = element.attribute( "changedirectory", "true") self.examples[uniqueName]['color'] = QtGui.QColor( element.attribute("color", "#f0f0f0")) if element.attribute("executable", "true") != "true": del self.examples[uniqueName] continue examplePath = None if sys.platform == "win32": examplePyName = exampleFileName + ".pyw" else: examplePyName = exampleFileName + ".py" if exampleDir.exists(examplePyName): examplePath = exampleDir.absoluteFilePath( examplePyName) elif exampleDir.cd(exampleFileName): if exampleDir.exists(examplePyName): examplePath = exampleDir.absoluteFilePath( examplePyName) if examplePath and not examplePath.isNull(): self.examples[uniqueName][ 'absolute path'] = exampleDir.absolutePath() self.examples[uniqueName]['path'] = examplePath self.categories[categoryName]['examples'].append( exampleName) else: del self.examples[uniqueName] self.categories[categoryName]['color'] = categoryColor return len(self.categories)
def __init__(self, parent=None): QDialog.__init__(self, parent) import Display import Geometry reload(Geometry) import Fur import Lights import RenderLayer reload(RenderLayer) import ShaderFix reload(ShaderFix) import RenderSettings reload(RenderSettings) import Utilities # Set up the user interface from Designer. loader = QtUiTools.QUiLoader() file = QtCore.QFile( "D:/zebratv/Projects/BOLO/software/AssemblingTK/src/LightingTK/ZebraLTK.ui" ) file.open(QtCore.QFile.ReadOnly) # myWidget = loader.load(file, self) self.ui = loader.load(file, self) self.ui.setWindowTitle('Zebra_LUT') self.ui.pushButton_GeoToBoxAll.clicked.connect( Display.DisplayGeoToBoxAll) self.ui.pushButton_BoxtoGeoAll.clicked.connect( Display.DisplayBoxToGeoAll) self.ui.pushButton_GeoToBox.clicked.connect(Display.DisplayBoundingBox) self.ui.pushButton_ChangeColor.clicked.connect(Display.ChangeColor) self.ui.pushButton_DisableOutliner.clicked.connect( Display.DisableColor) self.ui.pushButton_GeoSubdivision0.clicked.connect( Geometry.GeoSubdivision0) self.ui.pushButton_GeoSubdivision2.clicked.connect( Geometry.GeoSubdivision2) self.ui.pushButton_PrimaryVisibilityOff.clicked.connect( Geometry.PrimaryVisibilityOff) self.ui.pushButton_PrimaryVisibilityOn.clicked.connect( Geometry.PrimaryVisibilityOn) self.ui.pushButton_CastShadowsOff.clicked.connect( Geometry.CastShadowsOff) self.ui.pushButton_CastShadowsOn.clicked.connect( Geometry.CastShadowsOn) self.ui.pushButton_FixYetiRender.clicked.connect(Fur.FixYetiRender) self.ui.pushButton_YetiDisable.clicked.connect(Fur.YetiDisable) self.ui.pushButton_YetiEnable.clicked.connect(Fur.YetiEnable) self.ui.pushButton_FurDensity100.clicked.connect(Fur.FurDensity100) self.ui.pushButton_FurDensity50.clicked.connect(Fur.FurDensity50) self.ui.pushButton_FurDensity10.clicked.connect(Fur.FurDensity10) self.ui.pushButton_CheckFur.clicked.connect(Fur.YetiCheckFur) self.ui.FixElves_pushButton.clicked.connect(ShaderFix.FixElves) self.ui.pushButton_LocatorConstraint.clicked.connect( Lights.pointToLocator) LightRigFiles = os.listdir( 'D:\zebratv\Projects\BOLO\editorial\incoming\LightRigs\Environments/' ) LightRigFiles.sort() for lrf in LightRigFiles: if not lrf.startswith('.'): self.ui.listWidget_LightRigEnvironment.addItem( lrf.replace('_LightRig.mb', '')) self.ui.pushButton_LightRigEnvironment.clicked.connect( self.importlightRigEnv) LightRigCharacters = os.listdir( 'D:\zebratv\Projects\BOLO\editorial\incoming\LightRigs\Characters/' ) LightRigCharacters.sort() for lch in LightRigCharacters: if not lch.startswith('.'): self.ui.listWidget_LightRigCharacters.addItem( lch.replace('_LightRig.mb', '')) self.ui.pushButton_LightRigCharacters.clicked.connect( self.importLightRigChar) self.ui.pushButton_Characters.clicked.connect( RenderLayer.CreateGroupCharacters) self.ui.pushButton_GrpEnv.clicked.connect( RenderLayer.CreateGroupEnvironment) self.ui.pushButton_Environment_RL.clicked.connect( RenderLayer.RenderLayerEnvironment) self.ui.pushButton_CharacterOne_RL.clicked.connect( RenderLayer.CharacterOne) self.ui.pushButton_Characters_RL.clicked.connect( RenderLayer.Characters) self.ui.pushButton_CrowdsRL.clicked.connect(RenderLayer.Crowds) self.ui.pushButton_FogRL.clicked.connect(RenderLayer.RenderLayerFog) self.ui.pushButton_ShadowRL.clicked.connect( RenderLayer.RenderLayerShadow) self.ui.pushButton_FxRL.clicked.connect(RenderLayer.RenderLayerFx) self.ui.pushButton_RenderLayerClean.clicked.connect( RenderLayer.RenderLayerClean) self.ui.pushButton_Redshift.clicked.connect( RenderSettings.RedshiftRender) self.ui.pushButton_CleanScene.clicked.connect( Utilities.CleanShadingDelivery) self.ui.pushButton_CreateShaders.clicked.connect( Utilities.CreateShader) self.ui.pushButton_TransferShader.clicked.connect( Utilities.TransferShader) self.ui.pushButton_TextureReference.clicked.connect( Utilities.TexturureRef) self.ui.pushButton_Animation.clicked.connect( Utilities.GeoBakeAnimation) self.ui.pushButton_Transfer.clicked.connect(Utilities.TransferUvs) self.ui.pushButton_FxSettings.setText('Optimize Fur') self.ui.pushButton_FxSettings.clicked.connect( RenderSettings.FurShaderTransmisionDisable) self.ui.pushButton_FxSettings.setEnabled(True) file.close()