def highlightBlock(self, text): """@reimp @protected""" for pattern, format in self.highlightingRules: expression = QRegExp(pattern) index = expression.indexIn(text) while index >= 0: length = expression.matchedLength() self.setFormat(index, length, format) index = expression.indexIn(text, index + length) self.setCurrentBlockState(0) startIndex = 0 if self.previousBlockState() != 1: startIndex = self.commentStartExpression.indexIn(text) while startIndex >= 0: endIndex = self.commentEndExpression.indexIn(text, startIndex +1) if endIndex == -1: self.setCurrentBlockState(1) commentLength = len(text) - startIndex else: commentLength = endIndex - startIndex + self.commentEndExpression.matchedLength() self.setFormat(startIndex, commentLength, self.multiLineCommentFormat) startIndex = self.commentStartExpression.indexIn(text, startIndex + commentLength);
def __init__(self, parent, blackbold_patterns, redbold_patterns): ''' Define highlighting rules - inputs = lists of patterns ''' super(Highlighter, self).__init__(parent) self.highlighting_rules = [] # Black bold items (allowed keywords) black_bold_format = QTextCharFormat() black_bold_format.setFontWeight(QFont.Bold) self.highlighting_rules = [(QRegExp(pattern, cs=Qt.CaseInsensitive), black_bold_format) for pattern in blackbold_patterns] # Red bold items (reserved keywords) red_bold_format = QTextCharFormat() red_bold_format.setFontWeight(QFont.Bold) red_bold_format.setForeground(Qt.red) for pattern in redbold_patterns: self.highlighting_rules.append( (QRegExp(pattern, cs=Qt.CaseInsensitive), red_bold_format)) # Comments comment_format = QTextCharFormat() comment_format.setForeground(Qt.darkBlue) comment_format.setFontItalic(True) self.highlighting_rules.append((QRegExp('--[^\n]*'), comment_format))
def __init__(self, parent=None): QWidget.__init__(self, parent) self.__parent = parent self.setWindowTitle("Add Employee") self.id = QLineEdit(self) self.id.setValidator(QRegExpValidator(QRegExp("[a-zA-Z0-9-_]+"))) self.name = QLineEdit(self) self.name.setValidator(QRegExpValidator(QRegExp("[a-zA-Z\s]+"))) self.designation = QComboBox(self) # self.designation.addItems(DatabaseManager.db.getDesignations()) self.originalPay = QLineEdit(self) self.originalPay.setValidator(QDoubleValidator()) self.originalPayGrade = QLineEdit(self) self.originalPayGrade.setValidator(QDoubleValidator()) self.DOJ = DatePicker(self) self.pan = QLineEdit(self) self.pan.setValidator(QRegExpValidator(QRegExp("[A-Z]{5}\d{4}[A-Z]"))) self.bttnAddEmployee = QPushButton("Add Employee") self.bttnCancel = QPushButton("Cancel") self.bttnAddEmployee.setObjectName("OkButton") self.bttnCancel.setObjectName("CancelButton") self.bttnCancel.clicked.connect(self.goBack) self.bttnAddEmployee.clicked.connect(self.add) self.designation.addItems(DatabaseManager.db.getDesignations()) self.setupUI()
def __init__(self, parent=None): super().__init__(parent) regex = QRegExp(r"^M?M?M?(?:CM|CD|D?C?C?C?)" r"(?:XC|XL|L?X?X?X?)(?:IX|IV|V?I?I?I?)$") regex.setCaseSensitivity(Qt.CaseInsensitive) self.validator = QRegExpValidator(regex, self) self.setRange(1, 3999) self.lineEdit().textEdited.connect(self.fixCase)
def highlightBlock(self, text): for rule in self.highlighting_rules: expression = QRegExp(rule.pattern) index = expression.indexIn(text) while index >= 0: length = expression.matchedLength() self.setFormat(index, length, rule.format) index = expression.indexIn(text, index+length) self.setCurrentBlockState(0)
def on_text_change(self): ft = self.control.get_text() if self.use_fuzzy: reg = QRegExp('.*'.join(ft), Qt.CaseInsensitive) else: reg = QRegExp('^{}'.format(ft), Qt.CaseInsensitive) self.proxyModel.setFilterRegExp(reg) self.control.sortByColumn(0, self.proxyModel.sortOrder()) self.control.button.setEnabled(bool(ft))
def handleHtmlPage(self, htmlPage): tup = () self._gridList = [] wina7rx = QRegExp("\{\"pool_id\":700(\\d+).*\"pool_end\":(\\d+).*\"guaranteed_amount\":(\\d+).*\}") posi = wina7rx.indexIn(str(htmlPage)) ngrille = wina7rx.cap(1) print "ngrille=%s" % ngrille #self.gridList.append(wina7rx.cap(1)) date = wina7rx.cap(2) print "date=%s" % date jackpot = wina7rx.cap(3) print "jackpot=%s" % jackpot tup = (ngrille, date, jackpot) self._gridList.append(tup) while posi != -1 : posi = wina7rx.indexIn(str(htmlPage), posi+1) ngrille = wina7rx.cap(1) print "ngrille=%s" % ngrille date = wina7rx.cap(2) print "date=%s" % date jackpot = wina7rx.cap(3) print "jackpot=%s" % jackpot tup = (ngrille, date, jackpot) self._gridList.append(tup) print self._gridList
def variationFromString(self, string, caseSense=True): rx = QRegExp(self.variationRegExpPattern) rx.setMinimal(False) rx.setCaseSensitivity(Qt.CaseInsensitive) if caseSense: rx.setCaseSensitivity(Qt.CaseSensitive) index = rx.indexIn(string) length = rx.matchedLength() match = string[index:index + length] return match
def onTextChange(self, text): regExp = QRegExp() regExp.setPattern("[^0-9]*") m_correctText = "" if regExp.exactMatch(text): m_correctText = text QToolTip.hideText() else: point = QPoint(self.l.geometry().left(), self.l.geometry().bottom()) self.l.setText(m_correctText) QToolTip.showText(point, "Cannot enter number..")
def handleDistribHtmlPage(self, htmlPage): euro7startRx = QRegExp("data-grid-id=\"(\\d*)\"") indexGrille = "" posi = 0 while posi != -1 and indexGrille != self._gridList[self._indexGrille][0]: print "posi = %d" % posi print "indexGrille = %s" % indexGrille print "self._indexGrille = %s" % self._gridList[self._indexGrille][0] posi= euro7startRx.indexIn(htmlPage, posi+1) indexGrille = euro7startRx.cap(1) euro7TeamRx = QRegExp("<label for=\"[^\"]*\">([^<]*)<\/label>") self._grid = Grille() self._grid.setReturnRate(0.75) self._grid.setFirstRankRate(0.55) self._grid.setScndRankRate(0.45) jackpot = int(self._gridList[self._index][2]) self._grid.setJackpot(jackpot) self._grid.setNbPlayers(jackpot) index_l = 0 total = 0 #size_l = 5 i=0 #try: if True: posi= euro7TeamRx.indexIn(htmlPage, posi) print "posi = %d" % posi while posi != -1 and i < self._gridSize: i += 1 team1 = euro7TeamRx.cap(1) print "team1 = %s" % team1 posi= euro7TeamRx.indexIn(htmlPage, posi+1) posi= euro7TeamRx.indexIn(htmlPage, posi+1) team2 = euro7TeamRx.cap(1) print "indice %i" % i print "team2 = %s" % team2 match = Match(team1 + " vs " + team2) match.setTeam1(team1) match.setTeam2(team2) p1 = 0.33 pN = 0.33 p2 = 0.33 total = p1 + pN +p2 r1 = p1/total*100 r2 = p2/total*100 rN = pN/total*100 match.setRepartition(p1/total, pN/total, p2/total) self._grid.addGame(match) print "game added : %d" % i posi= euro7TeamRx.indexIn(htmlPage, posi+1) #except: #msg = QMessageBox() #msg.setText("Loading page error") #msg.exec_() #self.__workbook1.save(self.__outPutFileName) return
def setupTabs(self): """ Setup the various tabs in the AddressWidget. """ groups = ["ABC", "DEF", "GHI", "JKL", "MNO", "PQR", "STU", "VW", "XYZ"] for group in groups: proxyModel = QSortFilterProxyModel(self) proxyModel.setSourceModel(self.tableModel) proxyModel.setDynamicSortFilter(True) tableView = QTableView() tableView.setModel(proxyModel) tableView.setSortingEnabled(True) tableView.setSelectionBehavior(QAbstractItemView.SelectRows) tableView.horizontalHeader().setStretchLastSection(True) tableView.verticalHeader().hide() tableView.setEditTriggers(QAbstractItemView.NoEditTriggers) tableView.setSelectionMode(QAbstractItemView.SingleSelection) # This here be the magic: we use the group name (e.g. "ABC") to # build the regex for the QSortFilterProxyModel for the group's # tab. The regex will end up looking like "^[ABC].*", only # allowing this tab to display items where the name starts with # "A", "B", or "C". Notice that we set it to be case-insensitive. reFilter = "^[%s].*" % group proxyModel.setFilterRegExp(QRegExp(reFilter, Qt.CaseInsensitive)) proxyModel.setFilterKeyColumn(0) # Filter on the "name" column proxyModel.sort(0, Qt.AscendingOrder) #tableView.selectionModel().selectionChanged.connect(self.selectionChanged) self.addTab(tableView, group)
def __init__(self, parent=None): super(LoginWidget, self).__init__(parent) self._parent = parent self.title = "Log in" self.username = QtGui.QLineEdit(self) self.username.setPlaceholderText("Enter username") self.password = QtGui.QLineEdit(self) self.password.setPlaceholderText("Enter password") self.password.setEchoMode(QtGui.QLineEdit.Password) reg_ex = QRegExp("[a-zA-Z0-9-_]+") username_validator = QtGui.QRegExpValidator(reg_ex, self.username) self.username.setValidator(username_validator) self.password.returnPressed.connect(self.doLogin) self.showPass = QtGui.QCheckBox("Show Password") self.showPass.stateChanged.connect(self.handleShowPassword) self.bttnLogin = QtGui.QPushButton("Login", self) self.bttnLogin.setObjectName("LoginButton") self.bttnLogin.clicked.connect(self.doLogin) self.setupUI()
def __init__(self): self.regexp_str="Wait(?: at most "+Regexfloat+" secs)? for channel (\w) to reach "+Regexfloat+" \+/\- "+Regexfloat+" K" self.label="Wait(at most X secs) for channel X to reach X +/- X K" self.regexp_str="^ *"+self.regexp_str+" *$" #so that the same string with heading and trailing whitespaces also matches self.regexp=QRegExp(self.regexp_str) self.waiting=False self.waiting_start=0
class SetTempVTICommand(): def __init__(self): self.regexp_str="Set VTI Loop (\d+) to "+Regexfloat+" K(?: @ "+Regexfloat+" K/min)?" self.label="Set VTI Loop X to X K (@ X K/min)" self.regexp_str="^ *"+self.regexp_str+" *$" #so that the same string with heading and trailing whitespaces also matches self.regexp=QRegExp(self.regexp_str) self.waiting=False self.waiting_start=0 def run(self,main): values=self.regexp.capturedTexts() ##get the loop index and setpoint value loop=float(values[1]) setpoint=float(values[2]) #if a ramp rate was also provided, go to this setpoint at this rate VTI=main.instr_9 if values[3]!='': rate=float(values[3]) with main.reserved_access_to_instr: VTI.conf_ramp(loop,rate,'on') VTI.set_setpoint(loop,setpoint) else: with main.reserved_access_to_instr: VTI.switch_ramp(loop,'off') VTI.set_setpoint(loop,setpoint) #go to next line of macro after stdwtime (give some time to process other events) self.next_move=1 self.wait_time=500
def __init__(self): self.regexp_str="Set VTI Loop (\d+) to "+Regexfloat+" K(?: @ "+Regexfloat+" K/min)?" self.label="Set VTI Loop X to X K (@ X K/min)" self.regexp_str="^ *"+self.regexp_str+" *$" #so that the same string with heading and trailing whitespaces also matches self.regexp=QRegExp(self.regexp_str) self.waiting=False self.waiting_start=0
class AngleCommand(): def __init__(self): #Text that will appear in the list of commands on the right side of the Macro editor self.label="Set start|stop|step angle to FLOAT" #Regular expression which may or may not catch parameters self.regexp_str="Set (start|stop|step) angle to "+Regexfloat #Add this to the beginning and end of the regular expression #so that whitespaces before and after will not prevent the regex from matching self.regexp_str="^ *"+self.regexp_str+" *$" #instantiate regex self.regexp=QRegExp(self.regexp_str) def run(self,main): #what to do when the regex defined just above in __init__ #has matched the current line of the Macro #get the captured parameters values=self.regexp.capturedTexts() #set the corresponding angle box if values[1] in ['stop','step','start']: anglebox=eval("main.ui.angle"+values[1]) anglebox.setValue(float(values[2])) #Finally go to next line of macro... self.next_move=1 #...after 10 milliseconds self.wait_time=10
def __init__(self): self.regexp_str="Wait(?: at most "+Regexfloat+" secs)? for magnet (X|Y|Z) to finish ramping" self.label="Wait (at most X secs) for magnet (X|Y|Z) to finish ramping" self.regexp_str="^ *"+self.regexp_str+" *$" #so that the same string with heading and trailing whitespaces also matches self.regexp=QRegExp(self.regexp_str) self.waiting=False self.waiting_start=0
def __init__(self): self.regexp_str="Wait(?: at most "+Regexfloat+" secs)? for measurements completion" self.label="Wait(at most X secs) for measurements completion" self.regexp_str="^ *"+self.regexp_str+" *$" #so that the same string with heading and trailing whitespaces also matches self.regexp=QRegExp(self.regexp_str) self.waiting=False self.waiting_start=0
class WaitForHStableCommand(): def __init__(self): self.regexp_str="Wait(?: at most "+Regexfloat+" secs)? for magnet (X|Y|Z) to finish ramping" self.label="Wait (at most X secs) for magnet (X|Y|Z) to finish ramping" self.regexp_str="^ *"+self.regexp_str+" *$" #so that the same string with heading and trailing whitespaces also matches self.regexp=QRegExp(self.regexp_str) self.waiting=False self.waiting_start=0 def run(self,main): values=self.regexp.capturedTexts() #wait for field to stabilize (and lock only when accessing the instrument) with main.reserved_access_to_instr: magnet=eval("main.magnet_"+values[2]) stat=magnet.query_status() if self.waiting==False: self.waiting=True self.waiting_start=time.clock() if not(stat=='RAMPING to programmed current/field') or (values[1]!='' and time.clock()-self.waiting_start>float(values[1])): #ramping is finished or time limit is reached, go to next line of macro self.waiting=False self.next_move=1 self.wait_time=500 else: #wait 5s and check again self.next_move=0 self.wait_time=5000
def __init__(self, document): QSyntaxHighlighter.__init__(self, document) # Multi-line strings (expression, flag, style) # FIXME: The triple-quotes in these two lines will mess up the # syntax highlighting from this point onward self.tri_single = (QRegExp("'''"), 1, STYLES['string2']) self.tri_double = (QRegExp('"""'), 2, STYLES['string2']) rules = [] # Keyword, operator, and brace rules rules += [(r'\b%s\b' % w, 0, STYLES['keyword']) for w in PythonHighlighter.keywords] rules += [(r'%s' % o, 0, STYLES['operator']) for o in PythonHighlighter.operators] rules += [(r'%s' % b, 0, STYLES['brace']) for b in PythonHighlighter.braces] # All other rules rules += [ # 'self' (r'\bself\b', 0, STYLES['self']), # Double-quoted string, possibly containing escape sequences (r'"[^"\\]*(\\.[^"\\]*)*"', 0, STYLES['string']), # Single-quoted string, possibly containing escape sequences (r"'[^'\\]*(\\.[^'\\]*)*'", 0, STYLES['string']), # 'def' followed by an identifier (r'\bdef\b\s*(\w+)', 1, STYLES['defclass']), # 'class' followed by an identifier (r'\bclass\b\s*(\w+)', 1, STYLES['defclass']), # From '#' until a newline (r'#[^\n]*', 0, STYLES['comment']), # Numeric literals (r'\b[+-]?[0-9]+[lL]?\b', 0, STYLES['numbers']), (r'\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b', 0, STYLES['numbers']), (r'\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b', 0, STYLES['numbers']), ] # Build a QRegExp for each pattern self.rules = [(QRegExp(pat), index, fmt) for (pat, index, fmt) in rules]
def initHandlers(self): self.setWindowTitle(translateTitleMap[self.mode]) self.ui.cbLang.setCurrentIndex(self.wordInfo.srcLang.value) if self.wordModel.srcLang == utils.Lang.Eng: self.ui.leWord.setValidator( QRegExpValidator(QRegExp(utils.rxEng), self)) if self.wordModel.srcLang == utils.Lang.Rus: self.ui.leWord.setValidator( QRegExpValidator(QRegExp(utils.rxRus), self)) self.ui.leWord.setText(self.wordModel.wordValue) self.ui.teMeaning.setText(self.wordModel.wordMeaning) self.ui.btnCancel.clicked.connect(self._onCancel) self.ui.btnSave.clicked.connect(self._onOK) self.ui.actDownOrder.triggered.connect(self._onDownOrder) self.ui.actUpOrder.triggered.connect(self._onUpOrder) self.ui.actAddTranslate.triggered.connect(self._onAddTranslate)
def __init__(self): #Text that will appear in the list of commands on the right side of the Macro editor self.label="Set start|stop|step angle to FLOAT" #Regular expression which may or may not catch parameters self.regexp_str="Set (start|stop|step) angle to "+Regexfloat #Add this to the beginning and end of the regular expression #so that whitespaces before and after will not prevent the regex from matching self.regexp_str="^ *"+self.regexp_str+" *$" #instantiate regex self.regexp=QRegExp(self.regexp_str)
def __init__(self, parent=None): QWidget.__init__(self, parent) self.__parent = parent # ------elements for selecting employee----------- self.nameSearch = SearchBox(self) self.nameSearch.setPlaceholderText("Enter Name") self.nameSearch.returnPressed.connect(self.setIDList) # self.name.currentIndexChanged.connect(self.setIDList) self.nameList = [] self.nameList = DatabaseManager.db.getEmployeeNameList() self.nameSearch.setList(self.nameList) self.nameSearch.setCurrentIndex(-1) self.id = QComboBox() self.id.currentIndexChanged.connect(lambda: self.loadInfo(self.id.currentText())) # ------elements for ediiting employee----------- self.nameEdit = QLineEdit(self) self.nameEdit.setValidator(QRegExpValidator(QRegExp("[a-zA-Z\s]+"))) self.designation = QComboBox(self) self.originalPay = QLineEdit(self) self.originalPay.setValidator(QDoubleValidator()) self.originalPayGrade = QLineEdit(self) self.originalPayGrade.setValidator(QDoubleValidator()) self.DOJ = DatePicker(self) self.pan = QLineEdit(self) self.pan.setValidator(QRegExpValidator(QRegExp("[A-Z]{5}\d{4}[A-Z]"))) self.bttnSave = QPushButton("Save Changes") self.bttnCancel = QPushButton("Back") self.bttnSave.setObjectName("OkButton") self.bttnCancel.setObjectName("CancelButton") self.bttnCancel.clicked.connect(self.goBack) self.bttnSave.clicked.connect(self.save) self.designation.addItems(DatabaseManager.db.getDesignations()) self.nameSearch.editTextChanged.connect(self.clearInfo) self.clearInfo() self.setupUI()
def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.setupUi(self) #Validators for data input ipRange = "(?:[0-1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])" ipRegex = QRegExp("^" + ipRange + "\\." + ipRange + "\\." + ipRange + "\\." + ipRange + "$") ipValidator = QRegExpValidator(self.leGraylogIP) ipValidator.setRegExp(ipRegex) self.leGraylogIP.setValidator(ipValidator) self.leGraylogPort.setValidator(QIntValidator(1, 65535)) self.leGraylogHttpPort.setValidator(QIntValidator(1, 65535)) ipValidator = QRegExpValidator(self.leAsterixIP) ipValidator.setRegExp(ipRegex) self.leAsterixIP.setValidator(ipValidator) self.leAsterixPort.setValidator(QIntValidator(1, 65535)) self.leAsterixSic.setValidator(QIntValidator(1, 256)) self.leIamodPort.setValidator(QIntValidator(1, 65535)) self.leIamodThreshold.setValidator(QIntValidator(0, 99999)) #Define functions for GUI actions self.pbStart.clicked.connect(self.__startServer) self.pbStop.clicked.connect(self.__stopServer) self.actionLicense.triggered.connect(self.__license) self.actionLoad_Config_File.triggered.connect(self.__dialogConfigFile) self.pbSaveConfiguration.clicked.connect(self.__writeConfigFile) self.pbStart.setEnabled(False) if self.__checkServerIsRunning(): self.__serverStatusImage(True) else: self.__serverStatusImage(False) self.configFile = ConfigParser.ConfigParser() self.view = QWebView() self.webLayout.addWidget(self.view) self.view.settings().setAttribute( QWebSettings.JavascriptCanOpenWindows, True) self.view.settings().setAttribute(QWebSettings.LocalStorageEnabled, True) self.pbConnect.clicked.connect(self.__connectHttpServer) l = QVBoxLayout(self.tab2) sc = StaticCanvas(self.tab2, width=5, height=4, dpi=100) dc = DynamicCanvas(self.tab2, width=5, height=4, dpi=100) l.addWidget(sc) l.addWidget(dc)
def fill_ranking(self): rank = self.generation.ranking best = rank.ranking[0] rest = rank.ranking[1:] rx = QRegExp("pok\d+") best_pokelabels = self.ranking.findChildren(QtGui.QLabel, rx) for idx, pokename in enumerate(best.team_names): pixmap = QPixmap("./sprites/" + pokename + ".png") pixmap = pixmap.scaled(60, 40, QtCore.Qt.KeepAspectRatio) best_pokelabels[idx].setPixmap(pixmap) rx = QRegExp("poketeam_\d+") pop_teams = self.ranking.findChildren(QtGui.QWidget, rx) for g in range(len(rest)): plabel = pop_teams[g].findChildren(QtGui.QLabel) for idx, pokename in enumerate(rest[g].team_names): pixmap = QPixmap("./sprites/" + pokename + ".png") plabel[idx].setPixmap(pixmap)
def filterEdit(self): ret = QtWidgets.QLineEdit() #skqss.class_(ret, 'normal') ret.setPlaceholderText("%s ... (%s, %s)" % (tr_("Filter"), tr_("regular expression"), tr_("case-insensitive"))) ret.setToolTip("%s ... (%s, %s, Alt+F)" % (tr_("Filter"), tr_("regular expression"), tr_("case-insensitive"))) ret.textChanged.connect(lambda t: self.proxyModel.setFilterRegExp( QRegExp(t.strip(), Qt.CaseInsensitive) if t else None)) return ret
def highlightBlock(self, text): # Derived from Qt function, used to apply color-syntaxing to text # :param text: text input rules = [(QColor(100, 165, 225), r"^(//|#).+$"), #blue 100, 165, 225 (QColor(205, 200, 120), r"^(//|#) Warning.+$"), #yellow 205, 200, 120 (QColor(165, 75, 75), r"^(//|#).+Error.+$"), #red 165, 75, 75 (QColor(115, 215, 150), r"^(//|#).+Result.+$")] #green 115, 215, 150 # loop through rules for color, pattern in rules: keyword = QTextCharFormat() keyword.setForeground(color) # get regexp pattern expression = QRegExp(pattern) index = expression.indexIn(text) # loop until all matches are done while index >= 0: length = expression.matchedLength() # format text with current formatting self.setFormat(index, length, keyword) index = expression.indexIn(text, index + length) self.setCurrentBlockState(0)
class WaitCommand(): def __init__(self): self.regexp_str="Wait "+Regexfloat+" secs" self.label="Wait X secs" self.regexp_str="^ *"+self.regexp_str+" *$" #so that the same string with heading and trailing whitespaces also matches self.regexp=QRegExp(self.regexp_str) def run(self,main): values=self.regexp.capturedTexts() #self.values[1]!='' #go to next line of macro after 'values[1]' seconds self.next_move=1 self.wait_time=float(values[1])*1000
class SetSaveFileCommand(): def __init__(self): self.regexp_str="Set Save file to "+Regexsimplefile+"" self.label="Set Save file to X" self.regexp_str="^ *"+self.regexp_str+" *$" #so that the same string with heading and trailing whitespaces also matches self.regexp=QRegExp(self.regexp_str) def run(self,main): values=self.regexp.capturedTexts() main.ui.savefile_txt_input.setText(values[1]) #new file name is set, go to next line of macro self.next_move=1 self.wait_time=500
def createSettings(self): screen_res_box = QtGui.QHBoxLayout() screen_res_box.addWidget(QtGui.QLabel('Video resolution')) self.screenResolution = QtGui.QLineEdit('640x480') self.screenResolution.setValidator( QtGui.QRegExpValidator(QRegExp('[0-9]{3,}x[0-9]{3,}'), self.screenResolution)) self.screenResolution.textChanged.connect(self.check_state) self.screenResolution.textChanged.emit(self.screenResolution.text()) self.screenResolution.setEnabled(False) screen_res_box.addWidget(self.screenResolution) return self.BorderBox(screen_res_box)
def __init__(self, document): QSyntaxHighlighter.__init__(self, document) self.comments = (QRegExp(r"/\*"), QRegExp(r"\*/"), 1, STYLES['string2']) rules = [] # Keyword, operator, and brace rules rules += [(r'\b%s\b' % w, 0, STYLES['keyword']) for w in MelHighlighter.keywords] rules += [(r'\b%s\b' % w, 0, STYLES['string2']) for w in MelHighlighter.keywords2] rules += [(r'%s' % o, 0, STYLES['operator']) for o in MelHighlighter.operators] rules += [(r'%s' % b, 0, STYLES['brace']) for b in MelHighlighter.braces] # All other rules # Build a QRegExp for each pattern rules += [ # Numeric literals (r'\b[+-]?[0-9]+[lL]?\b', 0, STYLES['numbers']), (r'\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b', 0, STYLES['numbers']), (r'\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b', 0, STYLES['numbers']), # Double-quoted string, possibly containing escape sequences (r'"[^"\\]*(\\.[^"\\]*)*"', 0, STYLES['string']), # 'def' followed by an identifier (r'\bproc\b\s*(\w+)', 1, STYLES['defclass']), # 'class' followed by an identifier (r'\bglobal\b\s*(\w+)', 1, STYLES['defclass']), # From '//' until a newline (r'//[^\n]*', 0, STYLES['comment']), ] self.rules = [(QRegExp(pat), index, fmt) for (pat, index, fmt) in rules]
def initLineEdit(self): validator = QDoubleValidator() self.lineEdit_QDoubleValiator.setValidator(validator) validator = QIntValidator() self.lineEdit_CheckTying_int.setValidator(validator) self.lineEdit_CheckTying_int.textChanged.connect(self.check_state) self.lineEdit_CheckTying_int.textChanged.emit(self.lineEdit_CheckTying_int.text()) regExp = QRegExp('[A-C]\\d{5}[W-Z]') validator = QRegExpValidator(regExp) self.lineEdit_CheckTying_text.setValidator(validator) self.lineEdit_CheckTying_text.textChanged.connect(self.check_state) self.lineEdit_CheckTying_text.textChanged.emit(self.lineEdit_CheckTying_text.text())
def highlightBlock(self, text): """ Highlight a block of text """ if self.enabled is False: return text = unicode(text) original_text = text prev_data = self.currentBlock().previous().userData() if prev_data is not None: self._lexer._saved_state_stack = prev_data.syntax_stack elif hasattr(self._lexer, '_saved_state_stack'): del self._lexer._saved_state_stack # Lex the text using Pygments index = 0 for token, text in self._lexer.get_tokens(text): length = len(text) self.setFormat(index, length, self._get_format(token)) index += length if hasattr(self._lexer, '_saved_state_stack'): data = PygmentsBlockUserData( syntax_stack=self._lexer._saved_state_stack) self.currentBlock().setUserData(data) # Clean up for the next go-round. del self._lexer._saved_state_stack #Spaces expression = QRegExp('\s+') index = expression.indexIn(original_text, 0) while index >= 0: index = expression.pos(0) length = len(expression.cap(0)) self.setFormat(index, length, self._get_format(Whitespace)) index = expression.indexIn(original_text, index + length) self.hilighlightingBlock.emit(original_text, self)
class MacroHighlighter(QSyntaxHighlighter): def __init__(self,textboxdoc,valid_list_of_commands): QSyntaxHighlighter.__init__(self,textboxdoc) self.valid_syntax="|".join([command.regexp_str for command in valid_list_of_commands]) self.my_expression = QRegExp(self.valid_syntax) #define a blue font format for valid commands self.valid = QTextCharFormat() self.valid.setForeground(Qt.black) #define a bold red font format for invalid commands self.invalid = QTextCharFormat() self.invalid.setFontWeight(QFont.Bold) self.invalid.setForeground(Qt.red) #define a blue font format for valid parameters self.valid_value=QTextCharFormat() self.valid_value.setFontWeight(QFont.Bold) #self.valid_value.setForeground(QColor.fromRgb(255,85,0)) self.valid_value.setForeground(Qt.blue) def highlightBlock(self, text): #this function is automatically called when some text is changed #in the texbox. 'text' is the line of text where the change occured #check if the line of text contains a valid command match = self.my_expression.exactMatch(text) if match: #valid command found: highlight the command in blue self.setFormat(0, len(text), self.valid) #highlight the parameters in orange #loop on all the parameters that can be captured for i in range(self.my_expression.captureCount()): #if a parameter was captured, it's position in the text will be >=0 and its capture contains some value 'xxx' #otherwise its position is -1 and its capture contains an empty string '' if self.my_expression.pos(i+1)!=-1: self.setFormat(self.my_expression.pos(i+1), len(self.my_expression.cap(i+1)), self.valid_value) else: #no valid command found: highlight in red self.setFormat(0, len(text), self.invalid)
class SetVTIHeaterCommand(): def __init__(self): self.regexp_str="Set VTI heater range to (\d)" self.label="Set VTI heater range to DIGIT" self.regexp_str="^ *"+self.regexp_str+" *$" #so that the same string with heading and trailing whitespaces also matches self.regexp=QRegExp(self.regexp_str) def run(self,main): values=self.regexp.capturedTexts() #set the heater range with main.reserved_access_to_instr: main.instr_9.set_heater_range(int(values[1])) #go to next line of macro self.next_move=1 self.wait_time=500
def createEditor(self, parent, option, index): if index.column() == NODE_NAME: rename_editor = QLineEdit(parent) rename_editor.setValidator( QRegExpValidator(QRegExp(r'[a-zA-Z_]+[a-zA-Z0-9_:]*'), self)) return rename_editor elif index.column() == NODE_FILE: # filename_editor = QLineEdit(parent) filename_editor = PathEditor(parent, index) filename_editor.editingFinished.connect( self.commit_and_close_editor) return filename_editor else: return QStyledItemDelegate.createEditor(self, parent, option, index)
class WaitForEpoch(): def __init__(self): self.regexp_str="Wait for Epoch \+ "+Regexfloat+" secs" self.label="Wait for Epoch + X secs" self.regexp_str="^ *"+self.regexp_str+" *$" #so that the same string with heading and trailing whitespaces also matches self.regexp=QRegExp(self.regexp_str) def run(self,main): values=self.regexp.capturedTexts() #test if the current time is greater than the time provided in the macro (in Epoch seconds) if float(values[1])>time.time(): self.next_move=0 self.wait_time=5000 else: self.next_move=1 self.wait_time=100
def __init__(self,textboxdoc,valid_list_of_commands): QSyntaxHighlighter.__init__(self,textboxdoc) self.valid_syntax="|".join([command.regexp_str for command in valid_list_of_commands]) self.my_expression = QRegExp(self.valid_syntax) #define a blue font format for valid commands self.valid = QTextCharFormat() self.valid.setForeground(Qt.black) #define a bold red font format for invalid commands self.invalid = QTextCharFormat() self.invalid.setFontWeight(QFont.Bold) self.invalid.setForeground(Qt.red) #define a blue font format for valid parameters self.valid_value=QTextCharFormat() self.valid_value.setFontWeight(QFont.Bold) #self.valid_value.setForeground(QColor.fromRgb(255,85,0)) self.valid_value.setForeground(Qt.blue)
class SetVCommand(): def __init__(self): self.regexp_str="Set voltage (\d) to "+Regexfloat+" V" self.label="Set voltage DIGIT to FLOAT V" self.regexp_str="^ *"+self.regexp_str+" *$" #so that the same string with heading and trailing whitespaces also matches self.regexp=QRegExp(self.regexp_str) def run(self,main): values=self.regexp.capturedTexts() #set the voltage if values[1] in ['1','2','3']: V_source_setpoint=eval("main.ui.V_setpoint_"+values[1]) V_source_setpoint.setValue(float(values[2])) #go to next line of macro self.next_move=1 self.wait_time=500
class StartMeasureCommand(): def __init__(self): #type name_of_program() to start it self.regexp_str="Start "+Regexprogramfile+"\((.*)\)" self.label="Start PROGRAM()" self.regexp_str="^ *"+self.regexp_str+" *$" #so that the same string with heading and trailing whitespaces also matches self.regexp=QRegExp(self.regexp_str) def run(self,main): values=self.regexp.capturedTexts() main.ui.measMode.setCurrentIndex(main.ui.measMode.findText(values[1])) #start measurements main.start_measurements() #go to next line of macro self.next_move=1 self.wait_time=500
def __init__(self, parent=None): super(LoggingOptions, self).__init__() self.setTitle('Logging Options') self.layout = QVBoxLayout(self) self.chbox_include_timestamps = QCheckBox('Include timestamps') self.layout.addWidget(self.chbox_include_timestamps) self.chbox_equal_lines = QCheckBox(("Ignore if timestamps and values " "don't change")) self.layout.addWidget(self.chbox_equal_lines) self.hbox_bad_quality = QHBoxLayout(self) self.label_bad_quality = QLabel(('Value to log if reading ' 'quality is bad'), self) self.hbox_bad_quality.addWidget(self.label_bad_quality) self.le_bad_quality = QLineEdit(self) self.le_bad_quality.setText('bad') regex = QRegExp('[a-zA-Z0-9]+') validator = QRegExpValidator(regex) self.le_bad_quality.setValidator(validator) self.hbox_bad_quality.addWidget(self.le_bad_quality) self.layout.addLayout(self.hbox_bad_quality) self.hbox_separator = QHBoxLayout(self) self.label_separator = QLabel('CSV separator', self) self.hbox_separator.addWidget(self.label_separator) self.le_separator = QLineEdit(self) self.le_separator.setText(';') self.hbox_separator.addWidget(self.le_separator) self.layout.addLayout(self.hbox_separator) self.chbox_print_exceptions = QCheckBox(('Print exceptions as ' 'comment')) self.layout.addWidget(self.chbox_print_exceptions) self.hbox_comment_char = QHBoxLayout(self) self.label_comment_char = QLabel('Comment escape character', self) self.hbox_comment_char.addWidget(self.label_comment_char) self.le_comment_char = QLineEdit(self) self.le_comment_char.setText("'") self.hbox_comment_char.addWidget(self.le_comment_char) self.layout.addLayout(self.hbox_comment_char) self.setLayout(self.layout)
class SetICommand(): def __init__(self): self.regexp_str="Set current (\d) to "+Regexfloat+" A" self.label="Set current DIGIT to FLOAT A" self.regexp_str="^ *"+self.regexp_str+" *$" #so that the same string with heading and trailing whitespaces also matches self.regexp=QRegExp(self.regexp_str) def run(self,main): values=self.regexp.capturedTexts() #set the current if values[1]=='1': main.ui.I_source_setpoint.setValue(float(values[2])*1e6) elif values[1] in ['2','3']: I_source_setpoint=eval("main.ui.I_source_setpoint_"+values[1]) I_source_setpoint.setValue(float(values[2])*1e6) #go to next line of macro self.next_move=1 self.wait_time=10
class EmailCommand(): def __init__(self): self.regexp_str="E-mail message: "+Regexsimplefile self.label="E-mail message: MESSAGE" self.regexp_str="^ *"+self.regexp_str+" *$" #so that the same string with heading and trailing whitespaces also matches self.regexp=QRegExp(self.regexp_str) def run(self,main): values=self.regexp.capturedTexts() msg=values[1] try: email_alert=Email_alert(message=msg.encode('utf8'),address=main.ui.email_address.text(),subject="Message from PyGMI",smtpadd=main.mainconf['smtpadd'],login=main.mainconf['login'],mdp=main.mainconf['mdp'],smtpport=main.mainconf['smtpport']) print "message successfully sent by e-mail" except: print "Exception: message could not be sent by e-mail" #go to next line of macro self.next_move=1 self.wait_time=500
def __init__(self): super(StringParser, self).__init__() self._string = "" self._regExp = QRegExp("LOD[0-9]*[0-9]", Qt.CaseSensitive) self._regExpLOD = QRegExp("LOD[0-9]*[0-9]", Qt.CaseSensitive) self._regExpVariation = QRegExp("VAR[0-9]*[0-9]", Qt.CaseSensitive) self._resolutionsMap = { "1K": 1024, "2K": 2048, "3K": 3072, "4K": 4096, "5K": 5120, "6K": 6144, "7K": 7168, "8K": 8196 }
class SetPersistFieldCommand(): def __init__(self): self.regexp_str="Set persistent field in magnet (X|Y|Z) to "+Regexfloat+" T" self.label="Set persistent field in magnet X|Y|Z to x T" self.regexp_str="^ *"+self.regexp_str+" *$" #so that the same string with heading and trailing whitespaces also matches self.regexp=QRegExp(self.regexp_str) def run(self,main): values=self.regexp.capturedTexts() ##set the loop index and setpoint value magnet_setpoint=eval("main.ui.B_"+values[1]+"_setpoint") magnet_setpoint.setValue(float(values[2])) time.sleep(1) main.ui.measMode.setCurrentIndex(main.ui.measMode.findText("Change_persistent_"+values[1]+"_field")) #start measurements main.start_measurements() #go to next line of macro after stdwtime (give some time to process other events) self.next_move=1 self.wait_time=500
class EmailDirCommand(): def __init__(self): self.regexp_str="E-mail directory: "+Regexsimplefile self.label="E-mail directory: DIRECTORY" self.regexp_str="^ *"+self.regexp_str+" *$" #so that the same string with heading and trailing whitespaces also matches self.regexp=QRegExp(self.regexp_str) def run(self,main): values=self.regexp.capturedTexts() dir_path=values[1] try: message="Hi,\n\nat your request, here is the directory: "+os.path.normpath(os.path.abspath(dir_path.encode('utf8').strip()))+"\n\n PyGMI" email_alert=Email_directory(directory=dir_path.encode('utf8').strip(),address=main.ui.email_address.text(),message=message,subject="Data directory from PyGMI",smtpadd=main.mainconf['smtpadd'],login=main.mainconf['login'],mdp=main.mainconf['mdp'],smtpport=main.mainconf['smtpport']) print "directory successfully sent by e-mail" except: print "Exception: directory could not be sent by e-mail" #go to next line of macro self.next_move=1 self.wait_time=500
class WaitForTStableCommand(): def __init__(self): self.regexp_str="Wait(?: at most "+Regexfloat+" secs)? for channel (\w) to reach "+Regexfloat+" \+/\- "+Regexfloat+" K" self.label="Wait(at most X secs) for channel X to reach X +/- X K" self.regexp_str="^ *"+self.regexp_str+" *$" #so that the same string with heading and trailing whitespaces also matches self.regexp=QRegExp(self.regexp_str) self.waiting=False self.waiting_start=0 def run(self,main): values=self.regexp.capturedTexts() #wait for temperature to stabilize (and lock only when accessing the instrument) with main.reserved_access_to_instr: T=main.temp_controller.query_temp(values[2]) if self.waiting==False: self.waitTcounter=0 self.waiting=True self.waiting_start=time.clock() if values[1]!='' and time.clock()-self.waiting_start>float(values[1]): #time limit is reached, go to next line of macro self.waiting=False self.next_move=1 self.wait_time=500 elif abs(T-float(values[3]))<float(values[4]): #Wait for the temperature measurement to be ten times #within the specified limits, in a row, to consider it stable if self.waitTcounter<10: #count one, wait 0.5 secs and measure T again self.waitTcounter+=1 self.next_move=0 self.wait_time=500 else: #Temperature is stable, go to next line of macro self.waitTcounter=0 self.waiting=False self.next_move=1 self.wait_time=500 else: #wait 10s and check again, but reset the stable temperature counter self.waitTcounter=0 self.next_move=0 self.wait_time=10000
class SetFieldCommand(): def __init__(self): self.regexp_str="Set Field of magnet (X|Y|Z) to "+Regexfloat+" G(?: @ "+Regexfloat+" G/s)?" self.label="Set Field of magnet X|Y|Z to X G (@ X G/s)" self.regexp_str="^ *"+self.regexp_str+" *$" #so that the same string with heading and trailing whitespaces also matches self.regexp=QRegExp(self.regexp_str) def run(self,main): values=self.regexp.capturedTexts() with main.reserved_access_to_instr: magnet=eval("main.magnet_"+values[1]) if values[3]!='': #if a ramp rate was also provided, go to this setpoint at this rate magnet.program_ramp_rate_in_Gauss_per_second(float(values[3])) #print "Setting Field to ", magnet.program_field_in_kG(float(values[2])*1e-3) magnet.ramp_to_programmed_field() #go to next line of macro self.next_move=1 self.wait_time=500
def __init__(self, parent=None): super(ReadOptions, self).__init__() self.setTitle('Reading Options') self.layout = QVBoxLayout(self) self.label_poolling_rate = QLabel('Pooling Rate (ms)', self) self.layout.addWidget(self.label_poolling_rate) self.le_poolling_rate = QLineEdit(self) self.le_poolling_rate.setText('200') regex = QRegExp('[0-9]+') validator = QRegExpValidator(regex) self.le_poolling_rate.setValidator(validator) self.layout.addWidget(self.le_poolling_rate) self.chbox_sync = QCheckBox("Synchronous read") self.layout.addWidget(self.chbox_sync) self.setLayout(self.layout)
def check_completed_initialize(self): if self.thread.is_alive(): if (len(self.thread.gen.population) > 0 and len(self.thread.gen.population) <= 13): rx = QRegExp("poketeam_\d+") pop_teams = self.population.findChildren(QtGui.QWidget, rx) for g in range(len(self.thread.gen.population)): plabel = pop_teams[g].findChildren(QtGui.QLabel) for idx, pokename in enumerate( self.thread.gen.population[g].team_names): pixmap = QPixmap("./sprites/" + pokename + ".png") plabel[idx].setPixmap(pixmap) self.progress.setValue(len(self.thread.gen.population) * 10) QTimer.singleShot(50, self.check_completed_initialize) else: self.evolutionButton.setEnabled(True) self.generation = self.thread.gen self.progress.setValue(0) self.fill_ranking() self.statusbar.showMessage( "Done! Now press Calculate Generations to begin")
class WaitForMeasureCommand(): def __init__(self): self.regexp_str="Wait(?: at most "+Regexfloat+" secs)? for measurements completion" self.label="Wait(at most X secs) for measurements completion" self.regexp_str="^ *"+self.regexp_str+" *$" #so that the same string with heading and trailing whitespaces also matches self.regexp=QRegExp(self.regexp_str) self.waiting=False self.waiting_start=0 def run(self,main): values=self.regexp.capturedTexts() if self.waiting==False: self.waiting=True self.waiting_start=time.clock() if not(main.measurements_thread.isAlive()) or (values[1]!='' and time.clock()-self.waiting_start>float(values[1])): #Measurements are complete or time limit was reached, go to next line of macro self.waiting=False self.next_move=1 self.wait_time=500 else: #wait 1s and check again if measurements are complete self.next_move=0 self.wait_time=1000
def __init__(self, username=None, usingExportDialog=False): QtGui.QDialog.__init__(self) self._clips = [] self._sequences = [] # The Dialog can work in two modes, as a popover from the Bin View or via the main App Export window self.usingExportDialog = usingExportDialog self.username = username # setGeometry(x_pos, y_pos, width, height) self.setGeometry(240, 160, 726, 552) self.setStyleSheet( 'QWidget {background-color: #3B3E4A;} QLineEdit {color: #D0D5DC; border-color:#6F757F; border-width: 1px; border-radius: 4px; border-style: solid;} QLabel {color: #D0D5DC;}' ) self.setWindowTitle("Frame.io Uploader") #self.setAttribute( Qt.WA_TranslucentBackground, True ) self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint) self.setMouseTracking(True) self.draggable = True self.dragging_threshold = 0 self.__mousePressPos = None self.__mouseMovePos = None layout = QtGui.QVBoxLayout(self) layout.setAlignment(Qt.AlignCenter) self.toolBar = QtGui.QToolBar() self.toolBar.setStyleSheet( 'QToolBar {background-color: #3B3E4A; border-width: 0px; border-radius: 0px; border-style: none; text-align: center}' ) self.toolBar.setIconSize(QSize(24, 24)) self.closeButton = QtGui.QPushButton("") self.closeButton.setStyleSheet('QPushButton {border: none;}') iconClose = QtGui.QIcon(os.path.join(gIconPath, "close.png")) self.closeButton.setIcon(iconClose) self.closeButton.clicked.connect(self.close) iconLogout = QtGui.QIcon(os.path.join(gIconPath, "logout.png")) self.logoutToolBarAction = createMenuAction("", self.logoutPressed, icon=iconLogout) self.logoutToolBarAction.setVisible(False) self.logoutToolBarAction.setToolTip("Click here to Log out") self.unconnectedIndicatorPixmap = QtGui.QPixmap( os.path.join(gIconPath, "logo-unconnected.png")) self.connectedIndicatorPixmap = QtGui.QPixmap( os.path.join(gIconPath, "logo-connected.png")) self.connectionIndicatorLabel = QtGui.QLabel("Unconnected") spacer = QtGui.QWidget() spacer.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) self.toolBar.addWidget(self.closeButton) self.toolBar.addWidget(spacer) self.toolBar.addWidget(self.connectionIndicatorLabel) self.toolBar.addAction(self.logoutToolBarAction) layout.addWidget(self.toolBar) pixmap = QtGui.QPixmap(os.path.join(gIconPath, "frameio.png")) lbl = QtGui.QLabel("") lbl.setPixmap(pixmap) lbl.setAlignment(Qt.AlignCenter) layout.addWidget(lbl) font = QtGui.QFont() font.setPointSize(20) self.topLabel = QtGui.QLabel("Sign In") self.topLabel.setFont(font) self.topLabel.setAlignment(Qt.AlignCenter) layout.addWidget(self.topLabel) self.statusLabel = QtGui.QLabel("") self.statusLabel.setAlignment(Qt.AlignCenter) layout.addWidget(self.statusLabel) self.stackView = QtGui.QStackedWidget(self) # Login Screen View self.loginView = QtGui.QWidget() self.loginViewLayout = QtGui.QVBoxLayout(self) self.loginViewLayout.setAlignment(Qt.AlignCenter) self.emailLineEdit = QtGui.QLineEdit() self.emailLineEdit.setPlaceholderText("E-mail") self.emailLineEdit.setFont(font) self.emailLineEdit.setAlignment(Qt.AlignCenter) self.emailLineEdit.setFixedWidth(370) self.emailLineEdit.setFixedHeight(60) if self.username: self.emailLineEdit.setText(self.username) # Validator for checking email address is valid namerx = QRegExp("\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\\b") namerx.setCaseSensitivity(Qt.CaseInsensitive) namerx.setPatternSyntax(QRegExp.RegExp) self.nameval = QtGui.QRegExpValidator(namerx, self) self.emailLineEdit.setValidator(self.nameval) self.loginViewLayout.addWidget(self.emailLineEdit) self.passwordLineEdit = QtGui.QLineEdit() self.passwordLineEdit.setStyleSheet('') self.passwordLineEdit.setPlaceholderText("Password") self.passwordLineEdit.setFont(font) self.passwordLineEdit.setAlignment(Qt.AlignCenter) self.passwordLineEdit.setFixedWidth(370) self.passwordLineEdit.setFixedHeight(60) self.passwordLineEdit.setEchoMode(QtGui.QLineEdit.Password) self.loginViewLayout.addWidget(self.passwordLineEdit) self.submitButton = QtGui.QPushButton("LET'S GO") self.submitButton.setFlat(True) self.submitButton.setFont(font) self.submitButton.clicked.connect(self._submitButtonPressed) self.submitButton.setStyleSheet( 'QPushButton {width: 370px; height: 60px; border-width: 0px; border-radius: 4px; border-style: solid; background-color: #83DEBD; color: white;}' 'QPushButton:hover{background-color: #9974BA; }' 'QPushButton:pressed{background-color: #404040; border-width: 1px}' ) self.loginViewLayout.addWidget(self.submitButton) self.loginView.setLayout(self.loginViewLayout) self.stackView.addWidget(self.loginView) ### TO-DO - handle uploading of Clips via drag-drop into a dropzone # self.uploadDropzoneView = QtGui.QWidget() # self.uploadDropzoneView.setAcceptDrops(True) # Not hooked up. # self.uploadDropzoneLayout = QtGui.QVBoxLayout(self) # self.uploadDropzoneLayout.setAlignment(Qt.AlignCenter) # pixmap = QtGui.QPixmap(os.path.join(gIconPath, "uploadDropzone-64px.png")) # uploadIcon = QtGui.QLabel("") # uploadIcon.setPixmap(pixmap) # uploadIcon.setAlignment(Qt.AlignCenter) # self.uploadDropzoneLayout.addWidget(uploadIcon) # self.uploadDropzoneLabel1 = QtGui.QLabel("Upload your files") # self.uploadDropzoneLabel1.setAlignment(Qt.AlignCenter) # self.uploadDropzoneLabel1.setFont(font) # self.uploadDropzoneLabel2 = QtGui.QLabel("Drag 'n Drop your files or Clips/Sequences here.") # self.uploadDropzoneLabel1.setAlignment(Qt.AlignCenter) # self.uploadDropzoneLayout.addWidget(self.uploadDropzoneLabel1) # font.setPointSize(16) # self.uploadDropzoneLabel2.setFont(font) # self.uploadDropzoneLayout.addWidget(self.uploadDropzoneLabel2) # self.uploadDropzoneView.setLayout(self.uploadDropzoneLayout) # self.stackView.addWidget(self.uploadDropzoneView) ### View to handle uploading of Clips and Timelines View self.uploadView = QtGui.QWidget() self.uploadView.setStyleSheet( 'QPushButton {width: 100px; height: 100px; border-width: 0px; border-radius: 50px; border-style: solid; background-color: #9974BA; color: white;}' ) self.uploadViewLayout = QtGui.QVBoxLayout(self) self.uploadViewLayout.setAlignment(Qt.AlignCenter) self.uploadTopButtonWidget = QtGui.QWidget() self.uploadTopButtonLayout = QtGui.QHBoxLayout(self) self.uploadTopButtonLayout.setAlignment(Qt.AlignCenter) self.uploadTimelineOptionButton = QtGui.QPushButton("Timeline") self.uploadClipOptionButton = QtGui.QPushButton("Clips") self.uploadTimelineOptionButton.setCheckable(True) self.uploadTimelineOptionButton.setChecked(False) self.uploadTimelineOptionButton.setFont(font) self.uploadClipOptionButton.setCheckable(True) self.uploadClipOptionButton.setChecked(False) self.uploadClipOptionButton.setFont(font) self.uploadTopButtonLayout.addWidget(self.uploadTimelineOptionButton) self.uploadTopButtonLayout.addWidget(self.uploadClipOptionButton) self.uploadTopButtonWidget.setLayout(self.uploadTopButtonLayout) self.uploadBottomButtonWidget = QtGui.QWidget() self.uploadBottomButtonLayout = QtGui.QHBoxLayout(self) self.uploadBottomButtonLayout.setAlignment(Qt.AlignCenter) self.uploadCancelButton = QtGui.QPushButton("Cancel") self.uploadCancelButton.setStyleSheet( 'QPushButton {width: 170px; height: 70px; border-width: 0px; border-radius: 4px; border-style: solid; background-color: #767C8E; color: white;}' ) self.uploadCancelButton.clicked.connect(self.close) self.uploadTaskButton = QtGui.QPushButton("Done") self.uploadTaskButton.setStyleSheet( 'QPushButton {width: 170px; height: 70px; border-width: 0px; border-radius: 4px; border-style: solid; color: white;}' ) self.uploadTaskButton.clicked.connect(self._uploadButtonPushed) font.setPointSize(20) self.uploadCancelButton.setFont(font) self.uploadTaskButton.setFont(font) self.uploadBottomButtonLayout.addWidget(self.uploadCancelButton) self.uploadBottomButtonLayout.addWidget(self.uploadTaskButton) self.uploadBottomButtonWidget.setLayout(self.uploadBottomButtonLayout) self.projectWidget = QtGui.QWidget() self.projectWidgetLayout = QtGui.QHBoxLayout(self) self.projectDropdown = QtGui.QComboBox() self.projectDropdown.setFont(font) self.projectDropdown.setEditable(True) self.projectDropdown.lineEdit().setAlignment(Qt.AlignCenter) self.projectDropdown.setEditable(False) self.projectDropdown.setStyleSheet( 'QComboBox {width: 350px; height: 50px; border-width: 0px; border-radius: 4px; border-style: solid; background-color: #4F535F; color: white;}' ) self.projectRefreshButton = QtGui.QPushButton("Refresh") self.projectRefreshButton.setStyleSheet( 'QPushButton {width: 50px; height: 50px; border-width: 0px; border-radius: 25px; border-style: solid; background-color: #767C8E; color: white;}' ) self.projectRefreshButton.clicked.connect(self._refreshProjectList) self.projectWidgetLayout.addWidget(self.projectDropdown) self.projectWidgetLayout.addWidget(self.projectRefreshButton) self.projectWidget.setLayout(self.projectWidgetLayout) self.uploadViewLayout.addWidget(self.projectWidget) self.uploadViewLayout.addWidget(self.uploadBottomButtonWidget) self.uploadView.setLayout(self.uploadViewLayout) self.stackView.addWidget(self.uploadView) sizeGrip = QtGui.QSizeGrip(self) sizeGrip.setStyleSheet("QSizeGrip { height:12px; }") layout.addWidget(self.stackView) layout.addWidget(sizeGrip, 0, Qt.AlignBottom | Qt.AlignRight) self.setMinimumSize(160, 160) self.setLayout(layout) self.emailLineEdit.setFocus()
def __init__(self, delegate, usingExportDialog=False): QtGui.QDialog.__init__(self) self._clips = [] self._sequences = [] self.filePathsForUpload = [] # The Main FrameIOPySide AppDelegate self.delegate = delegate # The Dialog can work in two modes, as a popover from the Bin View or via the main App Export window self.usingExportDialog = usingExportDialog self.email = "" # setGeometry(x_pos, y_pos, width, height) self.setGeometry(240, 160, 726, 552) self.setStyleSheet('QWidget {background-color: #3B3E4A;} QLineEdit {color: #D0D5DC; border-color:#6F757F; border-width: 1px; border-radius: 4px; border-style: solid;} QLabel {color: #D0D5DC;}') self.setWindowTitle("Frame.io Uploader") #self.setAttribute( Qt.WA_TranslucentBackground, True ) self.setWindowFlags( Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint ) self.setMouseTracking(True) self.draggable = True self.dragging_threshold = 0 self.__mousePressPos = None self.__mouseMovePos = None layout = QtGui.QVBoxLayout(self) layout.setAlignment(Qt.AlignCenter) self.toolBar = QtGui.QToolBar() self.toolBar.setStyleSheet('QToolBar {background-color: #3B3E4A; border-width: 0px; border-radius: 0px; border-style: none; text-align: center}') self.toolBar.setIconSize( QSize(24,24) ) self.closeButton = QtGui.QPushButton("") self.closeButton.setStyleSheet('QPushButton {border: none;}') iconClose = QtGui.QIcon(os.path.join(gIconPath, "close.png")) self.closeButton.setIcon(iconClose) self.closeButton.clicked.connect(self.close) iconLogout = QtGui.QIcon(os.path.join(gIconPath, "logout.png")) self.logoutToolBarAction = createMenuAction("", self.logoutPressed, icon=iconLogout) self.logoutToolBarAction.setVisible(False) self.logoutToolBarAction.setToolTip("Click here to Log out") self.unconnectedIndicatorPixmap = QtGui.QPixmap(os.path.join(gIconPath, "logo-unconnected.png")) self.connectedIndicatorPixmap = QtGui.QPixmap(os.path.join(gIconPath, "logo-connected.png")) self.connectionIndicatorLabel = QtGui.QLabel("Unconnected") spacer = QtGui.QWidget() spacer.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) self.toolBar.addWidget(self.closeButton) self.toolBar.addWidget(spacer) self.toolBar.addWidget(self.connectionIndicatorLabel) self.toolBar.addAction(self.logoutToolBarAction) layout.addWidget(self.toolBar) pixmap = QtGui.QPixmap(os.path.join(gIconPath, "frameio.png")) lbl = QtGui.QLabel("") lbl.setPixmap(pixmap) lbl.setAlignment(Qt.AlignCenter) layout.addWidget(lbl) font = QtGui.QFont() font.setPointSize(20) self.topLabel = QtGui.QLabel("Login") self.topLabel.setFont(font) self.topLabel.setAlignment(Qt.AlignCenter) layout.addWidget(self.topLabel) self.statusLabel = QtGui.QLabel("") self.statusLabel.setAlignment(Qt.AlignCenter) layout.addWidget(self.statusLabel) self.stackView = QtGui.QStackedWidget(self) # Login Screen View self.loginView = QtGui.QWidget() self.loginViewLayout = QtGui.QVBoxLayout(self) self.loginViewLayout.setAlignment(Qt.AlignCenter) self.emailLineEdit = QtGui.QLineEdit() self.emailLineEdit.setPlaceholderText("E-mail") self.emailLineEdit.setFont(font) self.emailLineEdit.setAlignment(Qt.AlignCenter) self.emailLineEdit.setFixedWidth(370) self.emailLineEdit.setFixedHeight(60) if self.email: self.emailLineEdit.setText(self.email) self.emailLineEdit.setText("") # Validator for checking email address is valid namerx = QRegExp("\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\\b") namerx.setCaseSensitivity(Qt.CaseInsensitive); namerx.setPatternSyntax(QRegExp.RegExp); self.nameval = QtGui.QRegExpValidator(namerx, self) self.emailLineEdit.setValidator(self.nameval) self.loginViewLayout.addWidget(self.emailLineEdit) self.passwordLineEdit = QtGui.QLineEdit() self.passwordLineEdit.setStyleSheet('') self.passwordLineEdit.setPlaceholderText("Password") self.passwordLineEdit.setFont(font) self.passwordLineEdit.setAlignment(Qt.AlignCenter) self.passwordLineEdit.setFixedWidth(370) self.passwordLineEdit.setFixedHeight(60) self.passwordLineEdit.setEchoMode(QtGui.QLineEdit.Password) # Initially hide the password field, as we typically log in as Google Auth self.passwordLineEdit.setVisible(False) self.loginViewLayout.addWidget(self.passwordLineEdit) self.submitButton = QtGui.QPushButton("LET'S GO") self.submitButton.setFlat(True) self.submitButton.setFont(font) self.submitButton.clicked.connect(self._submitButtonPressed) self.submitButton.setStyleSheet('QPushButton {width: 370px; height: 60px; border-width: 0px; border-radius: 4px; border-style: solid; background-color: #83DEBD; color: white;}' 'QPushButton:hover{background-color: #9974BA; }' 'QPushButton:pressed{background-color: #404040; border-width: 1px}') self.loginViewLayout.addWidget(self.submitButton) # This WebView is used for Google OAuth2 Login self.webView = QWebView(parent=self) self.loginViewLayout.addWidget(self.webView) self.webView.setVisible(False) self.loginView.setLayout(self.loginViewLayout) self.stackView.addWidget(self.loginView) ### TO-DO - handle uploading of Clips via drag-drop into a dropzone self.uploadFilesView = QtGui.QWidget() self.uploadFilesView.setAcceptDrops(True) # Not hooked up. self.uploadDropzoneLayout = QtGui.QVBoxLayout(self) self.uploadDropzoneLayout.setAlignment(Qt.AlignCenter) pixmap = QtGui.QPixmap(os.path.join(gIconPath, "uploadDropzone-64px.png")) uploadIcon = QtGui.QLabel("") uploadIcon.setPixmap(pixmap) uploadIcon.setAlignment(Qt.AlignCenter) self.uploadDropzoneLayout.addWidget(uploadIcon) self.uploadDropzoneLabel1 = QtGui.QLabel("Upload your files") self.uploadDropzoneLabel1.setAlignment(Qt.AlignCenter) self.uploadDropzoneLabel1.setFont(font) self.uploadDropzoneLabel2 = QtGui.QLabel("Or choose files from picker...") self.uploadDropzoneLabel1.setAlignment(Qt.AlignCenter) self.uploadDropzoneLayout.addWidget(self.uploadDropzoneLabel1) font.setPointSize(16) self.uploadDropzoneLabel2.setFont(font) self.uploadDropzoneLayout.addWidget(self.uploadDropzoneLabel2) self.selectFilesButton = QtGui.QPushButton("Choose Files...") self.selectFilesButton.clicked.connect(self.showFilePicker) self.uploadDropzoneLayout.addWidget(self.selectFilesButton) self.uploadFilesView.setLayout(self.uploadDropzoneLayout) self.stackView.addWidget(self.uploadFilesView) ### View to handle uploading into a Project self.projectUploadView = QtGui.QWidget() self.projectUploadView.setStyleSheet('QPushButton {width: 100px; height: 100px; border-width: 0px; border-radius: 50px; border-style: solid; background-color: #9974BA; color: white;}') self.projectUploadViewLayout = QtGui.QVBoxLayout(self) self.projectUploadViewLayout.setAlignment(Qt.AlignCenter) self.uploadTopButtonWidget = QtGui.QWidget() self.uploadTopButtonLayout = QtGui.QHBoxLayout(self) self.uploadTopButtonLayout.setAlignment(Qt.AlignCenter) self.uploadTimelineOptionButton = QtGui.QPushButton("Timeline") self.uploadClipOptionButton = QtGui.QPushButton("Clips") self.uploadTimelineOptionButton.setCheckable(True) self.uploadTimelineOptionButton.setChecked(False) self.uploadTimelineOptionButton.setFont(font) self.uploadClipOptionButton.setCheckable(True) self.uploadClipOptionButton.setChecked(False) self.uploadClipOptionButton.setFont(font) self.uploadTopButtonLayout.addWidget(self.uploadTimelineOptionButton) self.uploadTopButtonLayout.addWidget(self.uploadClipOptionButton) self.uploadTopButtonWidget.setLayout(self.uploadTopButtonLayout) self.uploadBottomButtonWidget = QtGui.QWidget() self.uploadBottomButtonLayout = QtGui.QHBoxLayout(self) self.uploadBottomButtonLayout.setAlignment(Qt.AlignCenter) self.uploadCancelButton = QtGui.QPushButton("Cancel") self.uploadCancelButton.setStyleSheet('QPushButton {width: 170px; height: 70px; border-width: 0px; border-radius: 4px; border-style: solid; background-color: #767C8E; color: white;}') self.uploadCancelButton.clicked.connect(self.close) self.uploadTaskButton = QtGui.QPushButton("Done") self.uploadTaskButton.setStyleSheet('QPushButton {width: 170px; height: 70px; border-width: 0px; border-radius: 4px; border-style: solid; color: white;}') self.uploadTaskButton.clicked.connect(self._uploadButtonPushed) font.setPointSize(20) self.uploadCancelButton.setFont(font) self.uploadTaskButton.setFont(font) self.uploadBottomButtonLayout.addWidget(self.uploadCancelButton) self.uploadBottomButtonLayout.addWidget(self.uploadTaskButton) self.uploadBottomButtonWidget.setLayout(self.uploadBottomButtonLayout) self.projectWidget = QtGui.QWidget() self.projectWidgetLayout = QtGui.QHBoxLayout(self) self.projectDropdown = QtGui.QComboBox() self.projectDropdown.setFont(font) self.projectDropdown.setEditable(True) self.projectDropdown.lineEdit().setAlignment(Qt.AlignCenter) self.projectDropdown.setEditable(False) self.projectDropdown.setStyleSheet('QComboBox {width: 350px; height: 50px; border-width: 0px; border-radius: 4px; border-style: solid; background-color: #4F535F; color: white;}') self.projectRefreshButton = QtGui.QPushButton("Refresh") self.projectRefreshButton.setStyleSheet('QPushButton {width: 50px; height: 50px; border-width: 0px; border-radius: 25px; border-style: solid; background-color: #767C8E; color: white;}') self.projectRefreshButton.clicked.connect(self._refreshProjectList) self.projectWidgetLayout.addWidget(self.projectDropdown) #self.projectWidgetLayout.addWidget(self.projectRefreshButton) self.projectWidget.setLayout(self.projectWidgetLayout) self.projectUploadViewLayout.addWidget(self.projectWidget) self.projectUploadViewLayout.addWidget(self.uploadBottomButtonWidget) self.projectUploadView.setLayout(self.projectUploadViewLayout) self.stackView.addWidget(self.projectUploadView) sizeGrip = QtGui.QSizeGrip(self) sizeGrip.setStyleSheet("QSizeGrip { height:12px; }") layout.addWidget(self.stackView) layout.addWidget(sizeGrip, 0, Qt.AlignBottom | Qt.AlignRight); self.setMinimumSize(160, 160) self.setLayout(layout) self.emailLineEdit.setFocus()
def _getFreqValidator(): freqRegExp = QRegExp("^\\d*\.?\\d*[GgMm]?$") return QRegExpValidator(freqRegExp)
def __init__(self, delegate, username=None): super(FnFrameioWidget, self).__init__() global gIconPath self._clips = [] self._sequences = [] self.username = username # FrameioDelegate self.delegate = delegate #kwargs.get("delegate", None) # setGeometry(x_pos, y_pos, width, height) self.setGeometry(240, 160, 726, 552) self.setStyleSheet('QWidget {background-color: #3B3E4A;} QLineEdit {color: #D0D5DC; border-color:#6F757F; border-width: 1px; border-radius: 4px; border-style: solid;} QLabel {color: #D0D5DC;}') self.setWindowTitle("Frame.io Uploader") #self.setAttribute( Qt.WA_TranslucentBackground, True ) self.setWindowFlags( Qt.FramelessWindowHint ) self.setMouseTracking(True) self.draggable = True self.dragging_threshold = 0 self.__mousePressPos = None self.__mouseMovePos = None layout = QtGui.QVBoxLayout(self) layout.setAlignment(Qt.AlignCenter) self.toolBar = QtGui.QToolBar() self.toolBar.setStyleSheet('QToolBar {background-color: #3B3E4A; border-width: 0px; border-radius: 0px; border-style: none;}') self.closeButton = QtGui.QPushButton("") self.closeButton.setStyleSheet('QPushButton {border: none;}') icon = QtGui.QIcon(os.path.join(gIconPath + "close.png")) self.closeButton.setIcon(icon) self.closeButton.clicked.connect(self.close) self.toolBar.addWidget(self.closeButton) layout.addWidget(self.toolBar) pixmap = QtGui.QPixmap(os.path.join(gIconPath + "logo-64px.png")) lbl = QtGui.QLabel("") lbl.setPixmap(pixmap) lbl.setAlignment(Qt.AlignCenter) layout.addWidget(lbl) font = QtGui.QFont() font.setPointSize(20) self.topLabel = QtGui.QLabel("Sign In") self.topLabel.setFont(font) self.topLabel.setAlignment(Qt.AlignCenter) layout.addWidget(self.topLabel) self.statusLabel = QtGui.QLabel("") self.statusLabel.setAlignment(Qt.AlignCenter) layout.addWidget(self.statusLabel) self.stackView = QtGui.QStackedWidget(self) # Login Screen View self.loginView = QtGui.QWidget() self.loginViewLayout = QtGui.QVBoxLayout(self) self.loginViewLayout.setAlignment(Qt.AlignCenter) self.emailLineEdit = QtGui.QLineEdit() self.emailLineEdit.setPlaceholderText("E-mail") self.emailLineEdit.setFont(font) self.emailLineEdit.setAlignment(Qt.AlignCenter) self.emailLineEdit.setFixedWidth(370) self.emailLineEdit.setFixedHeight(60) if self.username: self.emailLineEdit.setText(self.username) # Validator for checking email address is valid namerx = QRegExp("\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\\b") namerx.setCaseSensitivity(Qt.CaseInsensitive); namerx.setPatternSyntax(QRegExp.RegExp); self.nameval = QtGui.QRegExpValidator(namerx, self) self.emailLineEdit.setValidator(self.nameval) self.loginViewLayout.addWidget(self.emailLineEdit) self.passwordLineEdit = QtGui.QLineEdit() self.passwordLineEdit.setStyleSheet('') self.passwordLineEdit.setPlaceholderText("Password") self.passwordLineEdit.setFont(font) self.passwordLineEdit.setAlignment(Qt.AlignCenter) self.passwordLineEdit.setFixedWidth(370) self.passwordLineEdit.setFixedHeight(60) self.passwordLineEdit.setEchoMode(QtGui.QLineEdit.Password) self.loginViewLayout.addWidget(self.passwordLineEdit) self.submitButton = QtGui.QPushButton("LET'S GO") self.submitButton.setFlat(True) self.submitButton.setFont(font) self.submitButton.clicked.connect(self._submitButtonPressed) self.submitButton.setStyleSheet('QPushButton {width: 370px; height: 60px; border-width: 0px; border-radius: 4px; border-style: solid; background-color: #83DEBD; color: white;}') self.loginViewLayout.addWidget(self.submitButton) self.loginView.setLayout(self.loginViewLayout) self.stackView.addWidget(self.loginView) ### View to handle uploading of Clips via drag-drop into a dropzone self.uploadDropzoneView = QtGui.QWidget() self.uploadDropzoneView.setAcceptDrops(True) # Not hooked up. self.uploadDropzoneLayout = QtGui.QVBoxLayout(self) self.uploadDropzoneLayout.setAlignment(Qt.AlignCenter) pixmap = QtGui.QPixmap(os.path.join(gIconPath + "uploadDropzone-64px.png")) uploadIcon = QtGui.QLabel("") uploadIcon.setPixmap(pixmap) uploadIcon.setAlignment(Qt.AlignCenter) self.uploadDropzoneLayout.addWidget(uploadIcon) self.uploadDropzoneLabel1 = QtGui.QLabel("Upload your files") self.uploadDropzoneLabel1.setAlignment(Qt.AlignCenter) self.uploadDropzoneLabel1.setFont(font) self.uploadDropzoneLabel2 = QtGui.QLabel("Drag 'n Drop your files or Clips/Sequences here.") self.uploadDropzoneLabel1.setAlignment(Qt.AlignCenter) self.uploadDropzoneLayout.addWidget(self.uploadDropzoneLabel1) font.setPointSize(16) self.uploadDropzoneLabel2.setFont(font) self.uploadDropzoneLayout.addWidget(self.uploadDropzoneLabel2) self.uploadDropzoneView.setLayout(self.uploadDropzoneLayout) self.stackView.addWidget(self.uploadDropzoneView) ### View to handle uploading of Clips and Timelines View self.uploadView = QtGui.QWidget() self.uploadView.setStyleSheet('QPushButton {width: 100px; height: 100px; border-width: 0px; border-radius: 50px; border-style: solid; background-color: #9974BA; color: white;}') self.uploadViewLayout = QtGui.QVBoxLayout(self) self.uploadViewLayout.setAlignment(Qt.AlignCenter) self.uploadTopButtonWidget = QtGui.QWidget() self.uploadTopButtonLayout = QtGui.QHBoxLayout(self) self.uploadTopButtonLayout.setAlignment(Qt.AlignCenter) self.uploadTimelineOptionButton = QtGui.QPushButton("Timeline") self.uploadClipOptionButton = QtGui.QPushButton("Clips") self.uploadTimelineOptionButton.setCheckable(True) self.uploadTimelineOptionButton.setChecked(False) self.uploadTimelineOptionButton.setFont(font) self.uploadClipOptionButton.setCheckable(True) self.uploadClipOptionButton.setChecked(False) self.uploadClipOptionButton.setFont(font) self.uploadTopButtonLayout.addWidget(self.uploadTimelineOptionButton) self.uploadTopButtonLayout.addWidget(self.uploadClipOptionButton) self.uploadTopButtonWidget.setLayout(self.uploadTopButtonLayout) # This will control whether annotations are uploaded into Frame.io for the item self.exportAnnotationsCheckbox = QtGui.QCheckBox("Export Tags+Annotations Text comments") self.uploadBottomButtonWidget = QtGui.QWidget() self.uploadBottomButtonLayout = QtGui.QHBoxLayout(self) self.uploadBottomButtonLayout.setAlignment(Qt.AlignCenter) self.uploadCancelButton = QtGui.QPushButton("Cancel") self.uploadCancelButton.setStyleSheet('QPushButton {width: 170px; height: 70px; border-width: 0px; border-radius: 4px; border-style: solid; background-color: #767C8E; color: white;}') self.uploadCancelButton.clicked.connect(self.showDropzoneUploadView) self.uploadTaskButton = QtGui.QPushButton("Upload") self.uploadTaskButton.setStyleSheet('QPushButton {width: 170px; height: 70px; border-width: 0px; border-radius: 4px; border-style: solid; color: white;}') self.uploadTaskButton.clicked.connect(self._uploadButtonPushed) font.setPointSize(20) self.uploadCancelButton.setFont(font) self.uploadTaskButton.setFont(font) self.uploadBottomButtonLayout.addWidget(self.uploadCancelButton) self.uploadBottomButtonLayout.addWidget(self.uploadTaskButton) self.uploadBottomButtonWidget.setLayout(self.uploadBottomButtonLayout) self.projectDropdown = QtGui.QComboBox() self.projectDropdown.setFont(font) self.projectDropdown.setEditable(True) self.projectDropdown.lineEdit().setAlignment(Qt.AlignCenter) self.projectDropdown.setEditable(False) self.projectDropdown.setStyleSheet('QComboBox {width: 350px; height: 50px; border-width: 0px; border-radius: 4px; border-style: solid; background-color: #4F535F; color: white;}') # We don't really need these FCP X style buttons because this acts upon a Selection #self.uploadViewLayout.addWidget(self.uploadTopButtonWidget) ### Enable when annotation uploads are supported #self.uploadViewLayout.addWidget(self.exportAnnotationsCheckbox) self.uploadViewLayout.addWidget(self.projectDropdown) self.uploadViewLayout.addWidget(self.uploadBottomButtonWidget) self.uploadView.setLayout(self.uploadViewLayout) self.stackView.addWidget(self.uploadView) sizeGrip = QtGui.QSizeGrip(self) sizeGrip.setStyleSheet("QSizeGrip { height:12px; }") layout.addWidget(self.stackView) layout.addWidget(sizeGrip, 0, Qt.AlignBottom | Qt.AlignRight); self.setMinimumSize(160, 160) self.setLayout(layout) self.emailLineEdit.setFocus()
def keyPressEvent(self, event): self.dirty = True customKey = False #AutoTab if (event.key() == Qt.Key_Enter or event.key() == 16777220): customKey = True numTab = 0 #new line newBlock = self.textCursor().block() currLine = newBlock.text() tabRE = QRegExp("^[\t]*") tabRE.indexIn(currLine) numTab = tabRE.matchedLength() if (currLine != "" and currLine.strip()[-1] == "{"): numTab += 1 QPlainTextEdit.keyPressEvent(self, event) if (numTab > 0): tCursor = self.textCursor() for _ in range(0, numTab): tCursor.insertText("\t") #automatic close brace if currLine != "" and currLine.strip()[-1] == "{": tCursor.insertText("\n") for _ in range(0, numTab - 1): tCursor.insertText("\t") tCursor.insertText("}") tCursor.movePosition(QTextCursor.PreviousBlock) tCursor.movePosition(QTextCursor.EndOfLine) self.setTextCursor(tCursor) if event.key() == Qt.Key_Tab and self.textCursor().hasSelection(): customKey = True selStart = self.textCursor().selectionStart() selEnd = self.textCursor().selectionEnd() cur = self.textCursor() endBlock = self.document().findBlock(selEnd) currBlock = self.document().findBlock(selStart) while currBlock.position() <= endBlock.position(): cur.setPosition(currBlock.position()) cur.insertText("\t") currBlock = currBlock.next() if event.key() == Qt.Key_Backtab and self.textCursor().hasSelection(): customKey = True selStart = self.textCursor().selectionStart() selEnd = self.textCursor().selectionEnd() cur = self.textCursor() endBlock = self.document().findBlock(selEnd) currBlock = self.document().findBlock(selStart) while currBlock.position() <= endBlock.position(): cur.setPosition(currBlock.position()) if currBlock.text().left(1) == "\t": cur.deleteChar() currBlock = currBlock.next() # Allow commenting and uncommenting of blocks of code if event.key() == Qt.Key_Slash and event.modifiers( ) == Qt.ControlModifier: customKey = True selStart = self.textCursor().selectionStart() selEnd = self.textCursor().selectionEnd() cur = self.textCursor() endBlock = self.document().findBlock(selEnd) currBlock = self.document().findBlock(selStart) while currBlock.position() <= endBlock.position(): cur.setPosition(currBlock.position()) if currBlock.text()[0] == "#": cur.deleteChar() # Make sure we remove extra spaces while currBlock.text()[0] == " ": cur.deleteChar() else: cur.insertText("# ") currBlock = currBlock.next() # Open the text finder if event.key() == Qt.Key_F and event.modifiers() == Qt.ControlModifier: customKey = True print("Opening finder...") if not customKey: QPlainTextEdit.keyPressEvent(self, event)
class StringParser(object): def __init__(self): super(StringParser, self).__init__() self._string = "" self._regExp = QRegExp("LOD[0-9]*[0-9]", Qt.CaseSensitive) self._regExpLOD = QRegExp("LOD[0-9]*[0-9]", Qt.CaseSensitive) self._regExpVariation = QRegExp("VAR[0-9]*[0-9]", Qt.CaseSensitive) self._resolutionsMap = { "1K": 1024, "2K": 2048, "3K": 3072, "4K": 4096, "5K": 5120, "6K": 6144, "7K": 7168, "8K": 8196 } @property def string(self): return self._string @property def regExpLOD(self): return self._regExpLOD @property def regExpVariation(self): return self._regExpVariation @property def regExp(self): return self._regExpVariation @string.setter def string(self, string): if not isinstance(string, str): raise TypeError("Expected < str >") self._string = string def clear(self): self._string = "" def resolutionFromString(self): for resolution in self._resolutionsMap: if self._string.find(resolution) != -1: res = self._resolutionsMap[resolution] return res, res def variation(self): index = self._regExpVariation.indexIn(self._string) length = self._regExpVariation.matchedLength() match = self._string[index:index + length] return match def LOD(self): index = self._regExpLOD.indexIn(self._string) length = self._regExpLOD.matchedLength() match = self._string[index:index + length] return match def find(self): """ Find by pattern and return first """ index = self._regExp.indexIn(self._string) length = self._regExp.matchedLength() match = self._string[index:index + length] return match def findAll(self): """ Find by pattern and return all """ index = 0 matches = [] while index >= 0: index = self._regExp.indexIn(self._string, index) length = self._regExp.matchedLength() print length match = self._string[index:index + length] index += length if match: matches.append(match) return matches
def testReplace1(self): re = QRegExp('a[mn]') string = re.replace('Banana', 'ox') self.assertEqual(string, 'Boxoxa')
def testReplace2(self): re = QRegExp('<i>([^<]*)</i>') string = re.replace('A <i>bon mot</i>.', '\\emph{\\1}') self.assertEqual(string, 'A \\emph{bon mot}.')
def highlightBlock(self, text): for h in self.singleline: expression = QRegExp(h.expression) index = expression.indexIn(text) while index >= 0: length = expression.matchedLength() self.setFormat(index, length, h.get_format()) index = expression.indexIn(text, index + length) for h in self.multiline: startIndex = 0 self.setCurrentBlockState(0) expression = QRegExp(h.expression) expression_end = QRegExp(h.expression_end) if (self.previousBlockState() != 1): startIndex = expression.indexIn(text) while startIndex >= 0: endIndex = expression_end.indexIn(text, startIndex + 1) if endIndex == -1: self.setCurrentBlockState(1) commentLength = len(text) - startIndex else: commentLength = endIndex - startIndex + \ expression_end.matchedLength() self.setFormat(startIndex, commentLength, h.get_format()) startIndex = expression.indexIn(text, startIndex + commentLength)