def try_to_play(self): if not self._was: self._was = True try: QCoreApplication.instance().beep() except: print("Beep wasn't played")
def showssd(self, param): if param == 'ALL' or param == 'OFF': qapp.postEvent(qapp.instance(), DisplayFlagEvent('SSD', param)) else: idx = self.sim.traf.id2idx(param) if idx >= 0: qapp.postEvent(qapp.instance(), DisplayFlagEvent('SSD', idx))
def updateContent(self): """ Clear the TreeView and refill it. """ #logging.debug(__name__ + ": updateContent") self.cancel() if self.dataAccessor() == None: return False self._updatingFlag += 1 self.clear() if self.dataObject() == None: self._updatingFlag -= 1 return True operationId = self._operationId i = 0 for object in self.applyFilter(self.dataObjects()): # Process application event loop in order to accept user input during time consuming drawing operation self._updateCounter += 1 if self._updateCounter >= self.UPDATE_EVERY: self._updateCounter = 0 if not Application.NO_PROCESS_EVENTS: QCoreApplication.instance().processEvents() # Abort drawing if operationId out of date if operationId != self._operationId: break self._createNode(object, self, str(i)) i += 1 if self._treeDepth > 0: self.expandToDepth(self._treeDepth - 1) self._updatingFlag -= 1 return self._operationId == operationId
def __init__(self, hintInfo, parent = None): super(InfoHintDialog,self).__init__(parent) self.setFixedSize(480, 290) language = StoreInfoParser.instance().getLanguage() m_pTranslator = QTranslator() exePath = "./" if language == "chinese": QmName = "zh_CN.qm" else: QmName = "en_US.qm" if(m_pTranslator.load(QmName, exePath)): QCoreApplication.instance().installTranslator(m_pTranslator) self.okBtn = QPushButton(self.tr("OK"), self) self.okBtn.setStyleSheet("background: rgb(7,87,198); color: white; width: 70px; height: 20px;font-size : 16px;") self.setTitle(self.tr("Tip Information")) self.hintInfo = hintInfo self.okBtn.move((self.width() - self.okBtn.width())/2, self.height() - self.okBtn.height() - 10) self.connect(self.okBtn, SIGNAL("clicked()"),self.slotOk)
def createConnections(self, operationId, widgetParent): for connection, values in self._connections.items(): # Process application event loop in order to accept user input during time consuming drawing operation self._updateCounter += 1 if self._updateCounter >= self.UPDATE_EVERY: self._updateCounter = 0 if not Application.NO_PROCESS_EVENTS: QCoreApplication.instance().processEvents() # Abort drawing if operationId out of date if operationId != self._operationId: return None w1 = self.widgetByObject(connection[0]) w2 = self.widgetByObject(connection[1]) if w1 and w2: if hasattr(w1, "colorIndex"): col = w1.colorIndex else: self._colorIndex += 1 if self._colorIndex >= len(self._colors): self._colorIndex = 0 col = self._colorIndex w1.colorIndex = col w2.colorIndex = col connectionWidget = self.createConnection( w1, values[0], w2, values[1], self._colors[col]) connectionWidget.show() return True
def on_CancelButton_clicked(self): """ Slot documentation goes here. """ # TODO: not implemented yet #QCoreApplication.quit() QCoreApplication.instance().quit()
def addProperty(self, bool=False): """ This function adds a property. The DataAcessor is called to add the property. """ type=str(self.sender()._typelist.currentText()) name=str(self.sender()._lineedit.text().toAscii()) if type in ["String","File"]: value="" elif type in ["Integer","Double"]: value=0 elif type in ["FileVector"]: value=() elif type in ["Boolean"]: value=False if name==None or name=="": QCoreApplication.instance().infoMessage("Please specify name of property.") return if self.dataAccessor(): if self.dataAccessor().addProperty(self.dataObject(), name, value, type): property=self.propertyWidgetFromProperty((type,name,value,None,False,True), self._currentCategoryName) if property: self.append(property) if isinstance(property,(FileProperty,FileVectorProperty)): property.useRelativePaths(self._relativePath) self.sender()._lineedit.setText("") property.setFocus() self.emit(SIGNAL('propertyAdded'),property.name())
def __init__(self): ApplicationBase.__init__(self) self.prefs = Preferences() self.prefs.load() global APP_PREFS APP_PREFS = self.prefs locale = QLocale.system() dateFormat = self.prefs.dateFormat decimalSep = locale.decimalPoint() groupingSep = locale.groupSeparator() cachePath = QDesktopServices.storageLocation(QDesktopServices.CacheLocation) appdata = getAppData() plugin_model_path = op.join(BASE_PATH, 'plugin_examples') DateEdit.DATE_FORMAT = dateFormat self.model = MoneyGuruModel( view=self, date_format=dateFormat, decimal_sep=decimalSep, grouping_sep=groupingSep, cache_path=cachePath, appdata_path=appdata, plugin_model_path=plugin_model_path ) # on the Qt side, we're single document based, so it's one doc per app. self.doc = Document(app=self) self.doc.model.connect() self.mainWindow = MainWindow(doc=self.doc) self.preferencesPanel = PreferencesPanel(self.mainWindow, app=self) self.aboutBox = AboutBox(self.mainWindow, self) if sys.argv[1:] and op.exists(sys.argv[1]): self.doc.open(sys.argv[1]) elif self.prefs.recentDocuments: self.doc.open(self.prefs.recentDocuments[0]) self.connect(self, SIGNAL('applicationFinishedLaunching()'), self.applicationFinishedLaunching) QCoreApplication.instance().aboutToQuit.connect(self.applicationWillTerminate)
def slotSave(self): language = StoreInfoParser.instance().getLanguage() m_pTranslator = QTranslator() exePath = "./" if language == "chinese": QmName = "zh_CN.qm" else: QmName = "en_US.qm" if(m_pTranslator.load(QmName, exePath)): QCoreApplication.instance().installTranslator(m_pTranslator) if not self.checkInputValid(): return if self.autoGetIpCheckbox.isChecked(): netconf = self.setDynamicNetwork() elif self.staticIpGroupbox.isChecked(): netconf = self.setStaticNetwork() #重新启动网络 self.restartNetworkTD.setNetConf(netconf) self.restartNetworkTD.start() return
def showssd(self, param): if param == "ALL" or param == "OFF": qapp.postEvent(qapp.instance(), DisplayFlagEvent("SSD", param)) else: idx = self.sim.traf.id2idx(param) if idx >= 0: qapp.postEvent(qapp.instance(), DisplayFlagEvent("SSD", idx))
def slotCheckPassWord(self): language = StoreInfoParser.instance().getLanguage() m_pTranslator = QTranslator() exePath = "./" if language == "chinese": QmName = "zh_CN.qm" else: QmName = "en_US.qm" if(m_pTranslator.load(QmName, exePath)): QCoreApplication.instance().installTranslator(m_pTranslator) passwd = self.passwordLineEdit.text() if passwd.isNull() or passwd.isEmpty(): self.showHintInfo(self.tr("Please input the password first!")) return #读取/etc/shadow文件,获取以root开头的行 crypasswd = self.getSystemAdministratorPassword() if not crypasswd: self.showHintInfo(self.tr("The password is not in shadow, can not check!")) return if not self.checkPasswd(passwd,crypasswd): self.showHintInfo(self.tr("The password is wrong, input again!")) return self.accept()
def macRightClick_userData_error_(self, pboard, data, error): log.trace("macRightClick has been called") try: types = pboard.types() pboardString = None if NSURLPboardType in types: pboardArray = pboard.propertyListForType_(NSURLPboardType) log.error("Retrieve property list stuff %r", pboardArray) for value in pboardArray: if value is None or value == "": continue # TODO Replug prompt_metadata on this one url = Foundation.NSURL.URLWithString_(value) if url is None: if value.startswith("file://"): value = value[7:] value = urllib2.unquote(value) else: value = url.path() log.debug("Should open : %s", value) from PyQt4.QtCore import QCoreApplication QCoreApplication.instance().show_metadata(value) return None except Exception as e: log.exception(e)
def updateToolList(self): self._toolList.clear() # import all tools and register them in toolsDict toolsFiles = [ os.path.join(self._toolsDir, f) for f in os.listdir(self._toolsDir) if f.endswith(".py") and not f.startswith("_") ] self._toolsDict = {} for toolsFile in toolsFiles: pythonModule = os.path.splitext(os.path.basename(toolsFile))[0] module = imp.load_source(pythonModule, toolsFile) for name in dir(module): tool = getattr(module, name) if inspect.isclass(tool) and issubclass( tool, ConfigToolBase) and not self._toolDataAccessor.label( tool) in self._toolsDict.keys( ) and not tool == ConfigToolBase: self._toolsDict[self._toolDataAccessor.label(tool)] = tool # Show test tool #from FWCore.GuiBrowsers.editorTools import ChangeSource #self._toolsDict["ChangeSource"]=ChangeSource if len(self._toolsDict) == 0 and self._toolsDir == standardToolsDir: logging.error( __name__ + ": Could not find any PAT tools. These will be available for the ConfigEditor in a future release." ) QCoreApplication.instance().errorMessage( "Could not find any PAT tools. These will be available for the ConfigEditor in a future release." ) return for item in self._toolsDict.keys(): self._toolList.addItem(item) self._toolList.sortItems()
def _fetch_indicators(self, progress=lambda val: None): """Background task for fetching indicators.""" progress(0) def row_item(display_value, item_values=None): """Generate a cell item for a given row.""" if not item_values: item_values = {} item = QtGui.QStandardItem() item.setData(display_value, Qt.DisplayRole) for role, value in item_values.items(): item.setData(value, role) return item progress(10) filter_ = self._main_widget.basic_indicator_filter() data = self._api.get_indicators(filter_=filter_) self._indicator_data = {ind["id"]: ind for ind in data} progress(70) indicators = [[""] + row for row in self._api.get_indicator_list(filter_=filter_)] model = QtGui.QStandardItemModel() model.setHorizontalHeaderLabels(indicators[0]) for row in indicators[1:]: search_string = " | ".join(row).lower() row_data = [row_item(item) for item in row] row_data[0].setData(search_string, TEXTFILTERROLE) row_data[1].setData(self._get_link(row[1]), gui.LinkRole) model.appendRow(row_data) progress(100) if QThread.currentThread() is not QCoreApplication.instance().thread(): model.moveToThread(QCoreApplication.instance().thread()) return model
def event(self,event): """ Call tabChanged if window is activated. """ if not self._tabWidget: if event.type()==QEvent.WindowActivate: QCoreApplication.instance().tabChanged() return QSplitter.event(self,event)
def updateContent(self, overrideCheck=False): """ Clear the BoxDecayView and refill it. """ logging.debug(__name__ + ": updateContent") self.cancel() if self.dataAccessor() == None: return False self._updatingFlag += 1 self.clear() if self.dataObject() == None: self._updatingFlag -= 1 return True operationId = self._operationId if not overrideCheck: if not self.checkNumberOfObjects(): self._updatingFlag -= 1 return False objects = self.applyFilter(self.dataObjects()) if self._sortBeforeArranging and self.arrangeUsingRelations(): thread = ThreadChain(self._sortByRelations, objects) while thread.isRunning(): if not Application.NO_PROCESS_EVENTS: QCoreApplication.instance().processEvents() objects = thread.returnValue() if operationId != self._operationId: self._updatingFlag -= 1 return False self.createBoxesRecursive(operationId, objects, self) # arrange objects which are not within a container BoxDecayContainer.autolayoutAlgorithm(self) self._updatingFlag -= 1 return operationId == self._operationId
def createConnections(self, operationId, widgetParent): """ Create connection lines between objects. In BoxDecayView default mother-daughter relations are vizualized by the connections. """ for w1 in widgetParent.children(): # Process application event loop in order to accept user input during time consuming drawing operation self._updateCounter += 1 if self._updateCounter >= self.UPDATE_EVERY: self._updateCounter = 0 if not Application.NO_PROCESS_EVENTS: QCoreApplication.instance().processEvents() # Abort drawing if operationId out of date if operationId != self._operationId: return None if isinstance(w1, ConnectableWidget): w1.setShowPortNames(False) for daughter in self.dataAccessor().daughterRelations( w1.object): if self.dataAccessor().isContainer( w1.object) or self.dataAccessor().isContainer( daughter): continue w2 = self.widgetByObject(daughter) if w2: connectionWidget = self.createConnection( w1, 'daughterRelations', w2, 'motherRelations', None, False) connectionWidget.stackUnder(w2) return True
def createConnections(self, operationId, widgetParent): """ Create connection lines between objects. In BoxDecayView default mother-daughter relations are vizualized by the connections. """ for w1 in widgetParent.children(): # Process application event loop in order to accept user input during time consuming drawing operation self._updateCounter+=1 if self._updateCounter>=self.UPDATE_EVERY: self._updateCounter=0 if not Application.NO_PROCESS_EVENTS: QCoreApplication.instance().processEvents() # Abort drawing if operationId out of date if operationId != self._operationId: return None if isinstance(w1, ConnectableWidget): w1.setShowPortNames(False) for daughter in self.dataAccessor().daughterRelations(w1.object): if self.dataAccessor().isContainer(w1.object) or self.dataAccessor().isContainer(daughter): continue w2 = self.widgetByObject(daughter) if w2: connectionWidget = self.createConnection(w1, 'daughterRelations', w2, 'motherRelations', None, False) connectionWidget.stackUnder(w2) return True
def updateContent(self, overrideCheck=False): """ Clear the BoxDecayView and refill it. """ logging.debug(__name__ + ": updateContent") self.cancel() if self.dataAccessor() == None: return False self._updatingFlag+=1 self.clear() if self.dataObject()==None: self._updatingFlag-=1 return True operationId = self._operationId if not overrideCheck: if not self.checkNumberOfObjects(): self._updatingFlag-=1 return False objects = self.applyFilter(self.dataObjects()) if self._sortBeforeArranging and self.arrangeUsingRelations(): thread = ThreadChain(self._sortByRelations, objects) while thread.isRunning(): if not Application.NO_PROCESS_EVENTS: QCoreApplication.instance().processEvents() objects=thread.returnValue() if operationId != self._operationId: self._updatingFlag -=1 return False self.createBoxesRecursive(operationId, objects, self) # arrange objects which are not within a container BoxDecayContainer.autolayoutAlgorithm(self) self._updatingFlag -=1 return operationId == self._operationId
def updateProcess(self, cp=True): logging.debug(__name__ + ": updateProcess") if cp: process = copy.deepcopy(self._processCopy) else: process = self.configDataAccessor().process() try: for tool in self._toolList: tool.apply(process) if not process.checkRecording(): logging.error(__name__ + ": Could not apply tool: " + self.label(tool) + " (problem with enable recording flag)") QCoreApplication.instance().errorMessage( "Could not apply tool: " + self.label(tool) + " (problem with enable recording flag)") return False except Exception as e: logging.error(__name__ + ": Could not apply tool: " + self.label(tool) + ": " + exception_traceback()) QCoreApplication.instance().errorMessage( "Could not apply tool (see log file for details):\n" + str(e)) return False self.configDataAccessor().setProcess(process) self._parameterErrors = {} return True
def slotSave(self): language = StoreInfoParser.instance().getLanguage() m_pTranslator = QTranslator() exePath = "./" if language == "chinese": QmName = "zh_CN.qm" else: QmName = "en_US.qm" if(m_pTranslator.load(QmName, exePath)): QCoreApplication.instance().installTranslator(m_pTranslator) """改变当前的分辨率""" screenName = self.resolutionCombox.itemData(0, Qt.UserRole + 1).toString() if not screenName.isEmpty() and not screenName.isNull(): self.curResolutionValue = self.getCurrentScreenResolution(str(screenName)) if self.curResolutionValue: reScreen = self.resolutionCombox.currentText() if reScreen == "800x600": pass else: pass #弹出提示框,默认为取消 rb = MessageBox(self.tr("making sure set the resolution to current"), self).exec_() if rb == QDialog.Accepted: self.jytcapi.jysetdispconf(str(reScreen)) elif rb == QDialog.Rejected: pass
def updateContent(self): """ Clear the TreeView and refill it. """ #logging.debug(__name__ + ": updateContent") self.cancel() if self.dataAccessor() == None: return False self._updatingFlag+=1 self.clear() if self.dataObject()==None: self._updatingFlag-=1 return True operationId = self._operationId i = 0 for object in self.applyFilter(self.dataObjects()): # Process application event loop in order to accept user input during time consuming drawing operation self._updateCounter+=1 if self._updateCounter>=self.UPDATE_EVERY: self._updateCounter=0 if not Application.NO_PROCESS_EVENTS: QCoreApplication.instance().processEvents() # Abort drawing if operationId out of date if operationId != self._operationId: break self._createNode(object, self, str(i)) i += 1 if self._treeDepth>0: self.expandToDepth(self._treeDepth-1) self._updatingFlag -=1 return self._operationId==operationId
def addProperty(self, bool=False): """ This function adds a property. The DataAcessor is called to add the property. """ type = str(self.sender()._typelist.currentText()) name = str(self.sender()._lineedit.text().toAscii()) if type in ["String", "File"]: value = "" elif type in ["Integer", "Double"]: value = 0 elif type in ["FileVector"]: value = () elif type in ["Boolean"]: value = False if name == None or name == "": QCoreApplication.instance().infoMessage( "Please specify name of property.") return if self.dataAccessor(): if self.dataAccessor().addProperty(self.dataObject(), name, value, type): property = self.propertyWidgetFromProperty( (type, name, value, None, False, True), self._currentCategoryName) if property: self.append(property) if isinstance(property, (FileProperty, FileVectorProperty)): property.useRelativePaths(self._relativePath) self.sender()._lineedit.setText("") property.setFocus() self.emit(SIGNAL('propertyAdded'), property.name())
def macRightClick_userData_error_(self, pboard, data, error): log.trace("macRightClick has been called") try: types = pboard.types() pboardString = None if NSURLPboardType in types: pboardArray = pboard.propertyListForType_(NSURLPboardType) log.error("Retrieve property list stuff %r", pboardArray) for value in pboardArray: if value is None or value == "": continue # TODO Replug prompt_metadata on this one url = Foundation.NSURL.URLWithString_(value) if url is None: if value.startswith("file://"): value = value[7:] value = urllib2.unquote(value) else: value = url.path() log.debug("Should open : %s", value) from PyQt4.QtCore import QCoreApplication QCoreApplication.instance().show_metadata(value) return None except Exception as e: log.exception(e)
def __init__(self,parent = None): super(MainFrame,self).__init__(parent) language = StoreInfoParser.instance().getLanguage() m_pTranslator = QTranslator() exePath = "./" if language == "chinese": QmName = "zh_CN.qm" StoreInfoParser.instance().setLanguage("chinese") else: QmName = "en_US.qm" if(m_pTranslator.load(QmName, exePath)): QCoreApplication.instance().installTranslator(m_pTranslator) #初始化子控件 self.initSubWidget() #绑定信号和槽 self.bandSignalSlot() self.setMinimumSize(800,600) self.showFullScreen() self.updateWidgetInfo() self.setPosition()
def slotShowRestartNetworkInfo(self, status): """显示重启网络的状态信息""" language = StoreInfoParser.instance().getLanguage() m_pTranslator = QTranslator() exePath = "./" if language == "chinese": QmName = "zh_CN.qm" else: QmName = "en_US.qm" if(m_pTranslator.load(QmName, exePath)): QCoreApplication.instance().installTranslator(m_pTranslator) if status == "Start": #InfoHintDialog(self.tr("restarting network, please wait ...")).exec_() self.waitingDlg.setHintInfo(self.tr("restarting network, please wait ...")) elif status == "Success": #InfoHintDialog(self.tr("network setting success")).exec_() self.waitingDlg.setHintInfo(self.tr("network setting success")) elif status == "Failed": #InfoHintDialog(self.tr("network restart failed")).exec_() self.waitingDlg.setHintInfo(self.tr("network restart failed")) else: return if self.waitingDlg.isHidden(): desktop = QApplication.desktop() self.waitingDlg.move((desktop.width() - self.waitingDlg.width())/2, (desktop.height() - self.waitingDlg.height())/2) self.waitingDlg.exec_()
def test_029_file_watcher(self): # Testing file watcher (filehandle,filename) = tempfile.mkstemp() with os.fdopen(filehandle,"w") as f: f.write("id,name\n1,rabbit\n2,pooh\n") QCoreApplication.instance().processEvents() def updatefile1( layer ): with file(filename,'a') as f: f.write('3,tigger\n') QCoreApplication.instance().processEvents() def updatefile2( layer ): with file(filename,'w') as f: f.write("name,size,id\ntoad,small,5\nmole,medium,6\nbadger,big,7\n") QCoreApplication.instance().processEvents() def deletefile( layer ): os.remove(filename) params={'geomType': 'none', 'type': 'csv', 'watchFile' : 'yes' } requests=[ {'fid': 3}, {}, {'fid': 7}, updatefile1, {'fid': 3}, {'fid': 4}, {}, {'fid': 7}, updatefile2, {'fid': 2}, {}, {'fid': 7}, deletefile, {'fid': 2}, {}, ] runTest(filename,requests,**params)
def createConnections(self, operationId, widgetParent): for connection, values in self._connections.items(): # Process application event loop in order to accept user input during time consuming drawing operation self._updateCounter += 1 if self._updateCounter >= self.UPDATE_EVERY: self._updateCounter = 0 if not Application.NO_PROCESS_EVENTS: QCoreApplication.instance().processEvents() # Abort drawing if operationId out of date if operationId != self._operationId: return None w1 = self.widgetByObject(connection[0]) w2 = self.widgetByObject(connection[1]) if w1 and w2: if hasattr(w1, "colorIndex"): col = w1.colorIndex else: self._colorIndex += 1 if self._colorIndex >= len(self._colors): self._colorIndex = 0 col = self._colorIndex w1.colorIndex = col w2.colorIndex = col connectionWidget = self.createConnection(w1, values[0], w2, values[1], self._colors[col]) connectionWidget.show() return True
def slotShowRestartNetworkInfo(self, status): """显示重启网络的状态信息""" language = StoreInfoParser.instance().getLanguage() m_pTranslator = QTranslator() exePath = "./" if language == "chinese": QmName = "zh_CN.qm" else: QmName = "en_US.qm" if(m_pTranslator.load(QmName, exePath)): QCoreApplication.instance().installTranslator(m_pTranslator) """显示重启网络的状态信息""" if status == "Start": self.waitingDlg.setHintInfo(self.tr("network is restarting, waiting...")) elif status == "Success": self.waitingDlg.setHintInfo(self.tr("network start success!")) vmtype = StoreInfoParser.instance().getVmType() if vmtype == "offline": pass elif status == "Failed": self.waitingDlg.setHintInfo(self.tr("network restart failed!")) else: return if self.waitingDlg.isHidden(): self.waitingDlg.exec_()
def _do_read(self): # Read messages from the socket and put them into the incoming queue # until nothing more can be read. while True: try: buf = self._socket.recv(4096) except socket.error as e: if e.errno in (errno.EAGAIN, errno.EWOULDBLOCK): break self._log.error("recv() error {0}".format(e.errno)) self.close() break if buf == b"": self._log.error("peer closed connection") self.close() break # XXX: should not be using protocol private attributes # Expose .error and .get_message() ? nbytes = self._protocol.data_received(buf) if self._protocol._error: self._log.error("parse error {0!s}", self._protocol._error) self.close() break while self._protocol._queue.qsize(): message = self._protocol._queue.get(block=False) self._incoming.append(message) # Schedule a dispatch if there are incoming messages if self._incoming: QCoreApplication.instance().postEvent(self, _Dispatch())
def rewritefile(layer): with file(filename, 'w') as f: f.write( "name,size,id\ntoad,small,5\nmole,medium,6\nbadger,big,7\n" ) # print "Rewritten file - sleeping" time.sleep(1) QCoreApplication.instance().processEvents()
def test_029_file_watcher(self): # Testing file watcher (filehandle, filename) = tempfile.mkstemp() with os.fdopen(filehandle, "w") as f: f.write("id,name\n1,rabbit\n2,pooh\n") QCoreApplication.instance().processEvents() def updatefile1(layer): with file(filename, 'a') as f: f.write('3,tigger\n') QCoreApplication.instance().processEvents() def updatefile2(layer): with file(filename, 'w') as f: f.write( "name,size,id\ntoad,small,5\nmole,medium,6\nbadger,big,7\n" ) QCoreApplication.instance().processEvents() def deletefile(layer): os.remove(filename) params = {'geomType': 'none', 'type': 'csv', 'watchFile': 'yes'} requests = [ { 'fid': 3 }, {}, { 'fid': 7 }, updatefile1, { 'fid': 3 }, { 'fid': 4 }, {}, { 'fid': 7 }, updatefile2, { 'fid': 2 }, {}, { 'fid': 7 }, deletefile, { 'fid': 2 }, {}, ] runTest(filename, requests, **params)
def deletefile(layer): try: os.remove(filename) except: file(filename, "w").close() assert os.path.getsize(filename) == 0, "removal and truncation of {} failed".format(filename) # print "Deleted file - sleeping" time.sleep(1) QCoreApplication.instance().processEvents()
def __init__(self, hintInfo="", parent = None): InfoHintDialog.__init__(self, hintInfo, parent) self.setStyleSheet("font-size : 16px") language = StoreInfoParser.instance().getLanguage() m_pTranslator = QTranslator() exePath = "./" if language == "chinese": QmName = "zh_CN.qm" else: QmName = "en_US.qm" if(m_pTranslator.load(QmName, exePath)): QCoreApplication.instance().installTranslator(m_pTranslator) self.setTitle(self.tr("Super Administrator")) self.passwordLabel = QLabel(self.tr("Root Password")) self.passwordLineEdit = QLineEdit() self.passwordLineEdit.setContextMenuPolicy(Qt.NoContextMenu) self.passwordLineEdit.setEchoMode(QLineEdit.Password) self.passwordLineEdit.setFocus(True) self.ensureBtn = QPushButton(self.tr("OK")) self.cancelBtn = QPushButton(self.tr("Cancel")) self.ensureBtn.setStyleSheet("background: rgb(7,87,198); color: white; width: 70px; height: 20px;font-size : 16px;") self.cancelBtn.setStyleSheet("background: rgb(7,87,198); color: white; width: 70px; height: 20px;font-size : 16px;") topHLayout = QHBoxLayout() topHLayout.addStretch() topHLayout.addWidget(self.passwordLabel) topHLayout.addSpacing(5) topHLayout.addWidget(self.passwordLineEdit) topHLayout.addStretch() bottomHLayout = QHBoxLayout() bottomHLayout.addStretch() bottomHLayout.addWidget(self.ensureBtn) bottomHLayout.addSpacing(10) bottomHLayout.addWidget(self.cancelBtn) bottomHLayout.addStretch() mainVLayout = QVBoxLayout() mainVLayout.addStretch() mainVLayout.addLayout(topHLayout) mainVLayout.addStretch() mainVLayout.addLayout(bottomHLayout) self.setLayout(mainVLayout) self.okBtn.hide() self.connect(self.ensureBtn, SIGNAL("clicked()"),self.slotCheckPassWord) self.connect(self.cancelBtn, SIGNAL("clicked()"),self.slotCancel) self.connect(self.okBtn, SIGNAL("clicked()"),self.slotOk)
def run(self): language = StoreInfoParser.instance().getLanguage() m_pTranslator = QTranslator() exePath = "./" if language == "chinese": QmName = "zh_CN.qm" else: QmName = "en_US.qm" if(m_pTranslator.load(QmName, exePath)): QCoreApplication.instance().installTranslator(m_pTranslator) desktop = QApplication.desktop() self.mypass = self.readText()#读取文件信息,内容为密码 if (self.lineEdit.text() == self.mypass): self.textArea.clear() self.lineEdit.clear() self.mymem = self.memory_stat()#返回内存信息 self.mydisk = self.disk_stat()#返回硬盘信息 self.mycpu = self.cpu_stat()#返回cpu信息 self.myload = self.load_stat()#返回负载信息 self.myuptime = self.uptime_stat()#返回运行时间 usedText = QString().number(self.mymem['MemUsed']) totalText = QString().number(self.mymem['MemTotal']) freeText = QString().number(self.mymem['MemFree']) buffersText = QString().number(self.mymem['Buffers']) cachedText = QString().number(self.mymem['Cached']) self.textArea.append(self.tr("Memory:")) self.textArea.append(self.tr("Total Memory:") + "\t" + totalText + " \tKB "+ "\r\n" + self.tr("Used Memory:") + "\t" + usedText+ " \tKB "+ "\r\n" + self.tr("Free Memory:") + "\t" + freeText+ " \tKB "+ "\r\n" +"Buffers:\t\t"+ buffersText+ " \tKB "+ "\r\n" +"Cached:\t\t"+ cachedText+ " \tKB ") #self.textArea.setText(text2) self.textArea.append(" ") self.textArea.append(self.tr("Disk:")) self.textArea.append(self.tr("Total Disk:") + "\t" + self.mydisk["total"]) self.textArea.append(" ") self.textArea.append(self.tr("Cpu Type:")) cpustr = "" for key in self.mycpu: curcpu = key + ": " + self.mycpu[key] + "\n" cpustr += curcpu self.textArea.append(cpustr) #self.textArea.append("\n") self.textArea.append(self.tr("Load information:")) self.textArea.append(self.tr("lavg_1:") + "\t" + self.myload['lavg_1'] +"\r\n" + self.tr("lavg_5:") + "\t" + self.myload['lavg_5'] +"\r\n" + self.tr("lavg_15:") + "\t" + self.myload['lavg_15'] +"\r\n" + self.tr("nr:") + "\t" + self.myload['nr'] +"\r\n" + self.tr("last_pid:") + "\t" + self.myload['last_pid']) self.textArea.append(" ") self.textArea.append(self.tr("Run Time:")) self.textArea.append(self.tr("Days:")+ "\t" + QString().number(self.myuptime['day']) + "\r\n" +self.tr("Hours:") + "\t" + QString().number(self.myuptime['hour']) + "\r\n" +self.tr("Minutes:") + "\t" + QString().number(self.myuptime['minute']) + "\r\n" +self.tr("Seconds:") + "\t" + QString().number(self.myuptime['second'])) a = self.floatToString(self.myuptime["Free rate"]) self.textArea.append(self.tr("Free Rate:")+ "\t" + a) self.textArea.append(" ") elif self.lineEdit.text() == "": InfoHintDialog(self.tr("password is empty")).exec_() self.textArea.clear() else: InfoHintDialog(self.tr("password is wrong")).exec_() self.lineEdit.clear()
def deletefile(layer): try: os.remove(filename) except: file(filename, "w").close() assert os.path.getsize( filename ) == 0, "removal and truncation of {} failed".format(filename) # print "Deleted file - sleeping" time.sleep(1) QCoreApplication.instance().processEvents()
def initLanguage(self): language = StoreInfoParser.instance().getLanguage() m_pTranslator = QTranslator() exePath = "./" if language == "chinese": QmName = "zh_CN.qm" else: QmName = "en_US.qm" if(m_pTranslator.load(QmName, exePath)): QCoreApplication.instance().installTranslator(m_pTranslator)
def readFile(self, filename): """ Reads in the file in a separate thread. """ self.cancel() self._thread = ThreadChain(self.dataAccessor().open, filename) while self._thread.isRunning(): if not Application.NO_PROCESS_EVENTS: QCoreApplication.instance().processEvents() if self._thread.returnValue(): self.updateEventNumberDisplay() return True return False
def set(self, rms, peak, decay): """ This is the main function, call this from any thread. 0.0 <= rms, peak, decay <= 1.0 """ t = time.time() * 0.1 if t - self._last_time > self.gov_sec: self._last_time = t e = QEvent(QEvent.User) e.rms = rms e.peak = peak e.decay = decay QCoreApplication.instance().postEvent(self, e)
def readFile(self, filename): """ Reads in the file in a separate thread. """ self.cancel() self._thread = ThreadChain(self.dataAccessor().open, filename) while self._thread.isRunning(): if not Application.NO_PROCESS_EVENTS: QCoreApplication.instance().processEvents() if self._thread.returnValue(): self.updateEventNumberDisplay() return True return False
def mousePressEvent(self, event): """ Makes sure event is forwarded to both base classes. If position of event is within the dropArea of a port a QMouseEvent is sent to the port. See dropArea(). """ dropAreaPort = self.dropAreaPort(event.pos()) if dropAreaPort and dropAreaPort.isDragable(): dropAreaPort.grabMouse() newEvent = QMouseEvent(event.type(), dropAreaPort.mapFromParent(event.pos()), event.button(), event.buttons(), event.modifiers()) QCoreApplication.instance().sendEvent(dropAreaPort, newEvent) else: VispaWidgetOwner.mousePressEvent(self, event) VispaWidget.mousePressEvent(self, event)
def abort(self, wait = False): self.stopping = True gc.collect() aliveGreenlets = self._countManagedGreenlets() if aliveGreenlets <= 0: QCoreApplication.instance().quit() else: logger.warning("Wait for %s greenlets to terminate.", aliveGreenlets) QTimer.singleShot(1000, self._foreToQuitApplication) if wait: assert self.greenlet is not greenlet.getcurrent(), \ "Can't abort with wait from inside the hub's greenlet." self.switch()
def mousePressEvent(self, event): """ Makes sure event is forwarded to both base classes. If position of event is within the dropArea of a port a QMouseEvent is sent to the port. See dropArea(). """ dropAreaPort = self.dropAreaPort(event.pos()) if dropAreaPort and dropAreaPort.isDragable(): dropAreaPort.grabMouse() newEvent = QMouseEvent(event.type(), dropAreaPort.mapFromParent(event.pos()), event.button(), event.buttons(), event.modifiers()) QCoreApplication.instance().sendEvent(dropAreaPort, newEvent) else: VispaWidgetOwner.mousePressEvent(self, event) VispaWidget.mousePressEvent(self, event)
def updateCenterView(self, propertyView=True): """ Fill the center view from an item in the TreeView and update it """ if not self._updateCenterView: # Do not update the very first time self._updateCenterView=True return statusMessage = self.plugin().application().startWorking("Updating center view") if propertyView: self.selectDataAccessor(True) else: self.selectDataAccessor(self.tab().propertyView().dataObject()) if self._thread != None and self._thread.isRunning(): self.dataAccessor().cancelOperations() while self._thread.isRunning(): if not Application.NO_PROCESS_EVENTS: QCoreApplication.instance().processEvents() objects = [] select=self.tab().treeView().selection() if select != None: if self.currentCenterViewClassId() == self.plugin().viewClassId(ConnectionStructureView): self.tab().centerView().setArrangeUsingRelations(True) if self.tab().centerView().checkNumberOfObjects(): if self.dataAccessor().isContainer(select): self._thread = ThreadChain(self.dataAccessor().readConnections, [select]+self.dataAccessor().allChildren(select)) else: self._thread = ThreadChain(self.dataAccessor().readConnections, [select], True) while self._thread.isRunning(): if not Application.NO_PROCESS_EVENTS: QCoreApplication.instance().processEvents() self.tab().centerView().setConnections(self._thread.returnValue()) self.tab().centerView().setDataObjects(self.dataAccessor().nonSequenceChildren(select)) else: self.tab().centerView().setDataObjects([]) elif self.currentCenterViewClassId() == self.plugin().viewClassId(SequenceStructureView): self.tab().centerView().setArrangeUsingRelations(False) self.tab().centerView().setDataObjects([select]) self.tab().centerView().setConnections({}) if (self.currentCenterViewClassId() == self.plugin().viewClassId(ConnectionStructureView) or self.currentCenterViewClassId() == self.plugin().viewClassId(SequenceStructureView)) and \ self.tab().centerView().updateContent(True): if not self.dataAccessor().isContainer(select) and self.currentCenterViewClassId() == self.plugin().viewClassId(ConnectionStructureView): self.tab().centerView().select(select,500) else: self.tab().centerView().restoreSelection() select = self.tab().centerView().selection() if select != None: if self.tab().propertyView().dataObject() != select and propertyView: self.tab().propertyView().setDataObject(select) self.tab().propertyView().updateContent() if import_tools_error==None and self.tab().editorSplitter(): self.updateConfigHighlight() self.plugin().application().stopWorking(statusMessage)
def abort(self, wait=False): self.stopping = True gc.collect() aliveGreenlets = self._countManagedGreenlets() if aliveGreenlets <= 0: QCoreApplication.instance().quit() else: logger.warning("Wait for %s greenlets to terminate.", aliveGreenlets) QTimer.singleShot(1000, self._foreToQuitApplication) if wait: assert self.greenlet is not greenlet.getcurrent(), \ "Can't abort with wait from inside the hub's greenlet." self.switch()
def appExit(self): #check the status of the dirty flag if self.dirty == False: #clean the temp folder if path.isfile('tmp/output.sqlite'): remove('tmp/output.sqlite') #and quit QCoreApplication.instance().quit() else: if self.okToContinue(): if path.isfile('tmp/output.sqlite'): remove('tmp/output.sqlite') QCoreApplication.instance().quit()
def apply(self): # allow property view to process parameter changes if not self.ok.hasFocus(): self._properties.clearFocus() self.ok.setFocus() return parameterErrors=self._toolDataAccessor.parameterErrors(self._selectedTool) if len(parameterErrors)>0: message="\n".join([error for error in parameterErrors]) QCoreApplication.instance().errorMessage(message) return ok=True if self._selectedTool: try: self._selectedTool.apply(self._toolDataAccessor.configDataAccessor().process()) if not self._toolDataAccessor.configDataAccessor().process().checkRecording(): ok=False logging.error(__name__ + ": Could not apply tool "+self._toolDataAccessor.label(self._selectedTool)+" (problem with enable recording flag) Please restart the ConfigEditor.") QCoreApplication.instance().errorMessage("Could not apply tool "+self._toolDataAccessor.label(self._selectedTool)+" (problem with enable recording flag) Please restart the ConfigEditor.") except Exception as e: ok=False logging.error(__name__ + ": Could not apply tool "+self._toolDataAccessor.label(self._selectedTool)+": "+exception_traceback()) QCoreApplication.instance().errorMessage("Cannot apply tool "+self._toolDataAccessor.label(self._selectedTool)+" (see log file for details):\n"+str(e)) else: ok=False logging.error(__name__ + ": Could not apply tool: No tool selected.") QCoreApplication.instance().errorMessage("Cannot apply tool: No tool selected.") # recover process copy to undo changes during the tool dialog self._toolDataAccessor.configDataAccessor().setProcess(self._processCopy) if ok: self.accept()
def _setupUi(self): self.setWindowTitle( tr("About {}").format( QCoreApplication.instance().applicationName())) self.resize(400, 190) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth()) self.setSizePolicy(sizePolicy) self.horizontalLayout = QHBoxLayout(self) self.logoLabel = QLabel(self) self.logoLabel.setPixmap(QPixmap(':/%s_big' % self.app.LOGO_NAME)) self.horizontalLayout.addWidget(self.logoLabel) self.verticalLayout = QVBoxLayout() self.nameLabel = QLabel(self) font = QFont() font.setWeight(75) font.setBold(True) self.nameLabel.setFont(font) self.nameLabel.setText(QCoreApplication.instance().applicationName()) self.verticalLayout.addWidget(self.nameLabel) self.versionLabel = QLabel(self) self.versionLabel.setText( tr("Version {}").format( QCoreApplication.instance().applicationVersion())) self.verticalLayout.addWidget(self.versionLabel) self.label_3 = QLabel(self) self.verticalLayout.addWidget(self.label_3) self.label_3.setText(tr("Copyright Hardcoded Software 2013")) self.label = QLabel(self) font = QFont() font.setWeight(75) font.setBold(True) self.label.setFont(font) self.verticalLayout.addWidget(self.label) self.registeredEmailLabel = QLabel(self) if self.withreg: self.registeredEmailLabel.setText(tr("UNREGISTERED")) self.verticalLayout.addWidget(self.registeredEmailLabel) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Ok) if self.withreg: self.registerButton = self.buttonBox.addButton( tr("Register"), QDialogButtonBox.ActionRole) self.verticalLayout.addWidget(self.buttonBox) self.horizontalLayout.addLayout(self.verticalLayout)
def install_gettext_trans_under_qt(base_folder, lang=None): # So, we install the gettext locale, great, but we also should try to install qt_*.qm if # available so that strings that are inside Qt itself over which I have no control are in the # right language. from PyQt4.QtCore import QCoreApplication, QTranslator, QLocale, QLibraryInfo if not lang: lang = str(QLocale.system().name())[:2] localename = get_locale_name(lang) if localename is not None: try: locale.setlocale(locale.LC_ALL, localename) except locale.Error: logging.warning("Couldn't set locale %s", localename) qmname = 'qt_%s' % lang if ISLINUX: # Under linux, a full Qt installation is already available in the system, we didn't bundle # up the qm files in our package, so we have to load translations from the system. qmpath = op.join(QLibraryInfo.location(QLibraryInfo.TranslationsPath), qmname) else: qmpath = op.join(base_folder, qmname) qtr = QTranslator(QCoreApplication.instance()) qtr.load(qmpath) QCoreApplication.installTranslator(qtr) install_gettext_trans(base_folder, lang)
def _setupUi(self): appname = QCoreApplication.instance().applicationName() title = tr("$appname is Fairware") title = title.replace('$appname', appname) self.setWindowTitle(title) # Workaround for bug at http://bugreports.qt.nokia.com/browse/QTBUG-8212 dlg_height = 370 if ISLINUX else 240 self.resize(400, dlg_height) self.verticalLayout = QVBoxLayout(self) self.descLabel = QLabel(self) self.descLabel.setWordWrap(True) self.verticalLayout.addWidget(self.descLabel) spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.verticalLayout.addItem(spacerItem) self.horizontalLayout = QHBoxLayout() self.tryButton = QPushButton(self) self.tryButton.setText(tr("Try")) self.horizontalLayout.addWidget(self.tryButton) self.enterCodeButton = QPushButton(self) self.enterCodeButton.setText(tr("Enter Key")) self.horizontalLayout.addWidget(self.enterCodeButton) self.buyButton = QPushButton(self) self.buyButton.setText(tr("Buy")) self.horizontalLayout.addWidget(self.buyButton) self.moreInfoButton = QPushButton(tr("Fairware?")) self.horizontalLayout.addWidget(self.moreInfoButton) self.verticalLayout.addLayout(self.horizontalLayout)
def buttonClicked(self, checked=False): """ Shows the file selection dialog. """ if isinstance(self._originalValue, type(())) and len(self._originalValue)>0: dir=os.path.dirname(self._originalValue[0]) elif self._relativePath: dir=self._relativePath else: dir=QCoreApplication.instance().getLastOpenLocation() fileList = QFileDialog.getOpenFileNames( self, 'Select a list of files', dir, '', None, QFileDialog.DontConfirmOverwrite) fileNames=[str(f) for f in fileList] if self._relativePath: nfileNames=[] for v in fileNames: if v.startswith(self._relativePath): nfileNames+=[v[len(self._relativePath):].lstrip("/")] else: nfileNames+=[v] fileNames=nfileNames if len(fileNames)>0: self.setValue(fileNames) self.textEdit().emit(SIGNAL('editingFinished()'))
def _setup(self): self._setupActions() self._update_options() self.recentResults = Recent(self, 'recentResults') self.recentResults.mustOpenItem.connect(self.model.load_from) self.resultWindow = self.RESULT_WINDOW_CLASS(self) self.progress_window = ProgressWindow(self.resultWindow, self.model.progress_window) self.directories_dialog = DirectoriesDialog(self.resultWindow, self) self.details_dialog = self.DETAILS_DIALOG_CLASS( self.resultWindow, self) self.problemDialog = ProblemDialog(parent=self.resultWindow, model=self.model.problem_dialog) self.ignoreListDialog = IgnoreListDialog( parent=self.resultWindow, model=self.model.ignore_list_dialog) self.deletionOptions = DeletionOptions( parent=self.resultWindow, model=self.model.deletion_options) self.preferences_dialog = self.PREFERENCES_DIALOG_CLASS( self.resultWindow, self) self.about_box = AboutBox(self.resultWindow, self) self.directories_dialog.show() self.model.load() # The timer scheme is because if the nag is not shown before the application is # completely initialized, the nag will be shown before the app shows up in the task bar # In some circumstances, the nag is hidden by other window, which may make the user think # that the application haven't launched. QTimer.singleShot(0, self.finishedLaunching) self.connect(QCoreApplication.instance(), SIGNAL('aboutToQuit()'), self.application_will_terminate)
def __init__(self, *args, **kwargs): """Initialize this instance.""" super(WebClient, self).__init__(*args, **kwargs) self.nam = QNetworkAccessManager(QCoreApplication.instance()) self.nam.finished.connect(self._handle_finished) self.nam.authenticationRequired.connect(self._handle_authentication) self.nam.proxyAuthenticationRequired.connect(self.handle_proxy_auth) self.nam.sslErrors.connect(self._handle_ssl_errors) self.replies = {} self.proxy_retry = False self.setup_proxy() # Force Qt to load the system certificates QSslSocket.setDefaultCaCertificates(QSslSocket.systemCaCertificates()) # Apply our local certificates as the SSL configuration to be used # for all QNetworkRequest calls. self.ssl_config = QSslConfiguration.defaultConfiguration() ca_certs = self.ssl_config.caCertificates() try: for path in glob.glob( os.path.join(get_cert_dir(), "UbuntuOne*.pem")): with open(path) as f: cert = QSslCertificate(f.read()) if cert.isValid(): ca_certs.append(cert) else: logger.error("invalid certificate: {}".format(path)) except (IndexError, IOError) as err: raise WebClientError( "Unable to configure SSL certificates: {}".format(err)) self.ssl_config.setCaCertificates(ca_certs)
def __init__(self): self._reads = {} self._writes = {} self._notifiers = {} self._timer = QTimer() self._timer.setSingleShot(True) QObject.connect(self._timer, SIGNAL("timeout()"), self.iterate) if QCoreApplication.instance() is None: # Application Object has not been started yet self.qApp = QCoreApplication([]) self._ownApp = True else: self.qApp = QCoreApplication.instance() self._ownApp = False self._blockApp = None posixbase.PosixReactorBase.__init__(self)
def filter(self): logging.debug(__name__ +': filter') self._findNextButton.setVisible(False) self._filterButton.setVisible(False) self._resetButton.setVisible(False) self._findNumberLabel.setText("Searching...") self._findNumberLabel.show() thread = ThreadChain(self._findAlgorithm.findUsingFindDialog, self) while thread.isRunning(): if not Application.NO_PROCESS_EVENTS: QCoreApplication.instance().processEvents() if self._find: self._findNextButton.setVisible(True) self._filterButton.setVisible(True) self._resetButton.setVisible(True) self._updateNumberLabel() self.emit(SIGNAL("filtered"),self._findAlgorithm.results())
def selectInputFile(self): filename = str(QFileDialog.getOpenFileName(self, 'Select input file', QCoreApplication.instance().getLastOpenLocation(), "Dataformat file / EDM root file (*.txt *.root)")) if filename!="": self._inputFileName=filename self.updateContent()
def cleanCatalog(cat): for groupName in [GROUP, GEOLOGY_GROUP]: def _del_group(groupName, cat): group = cat.get_layergroup(groupName) if group is not None: cat.delete(group) group = cat.get_layergroup(groupName) assert group is None _del_group(groupName, cat) # Try with namespaced _del_group("%s:%s" % (WORKSPACE, groupName), cat) toDelete = [] for layer in cat.get_layers(): if layer.name.startswith(PREFIX): toDelete.append(layer) for style in cat.get_styles(): if style.name.startswith(PREFIX): toDelete.append(style) for e in toDelete: try: cat.delete(e, purge=True) except: from PyQt4.QtCore import QCoreApplication while 1: QCoreApplication.instance().processEvents() for ws in cat.get_workspaces(): if not ws.name.startswith(PREFIX): continue if ws is not None: for store in cat.get_stores(ws): for resource in store.get_resources(): try: cat.delete(resource) except: pass cat.delete(store) cat.delete(ws) ws = cat.get_workspace(ws.name) assert ws is None
def __init__(self): #self.setWindowIcon(QIcon("icon.png")) QMainWindow.__init__(self) myappid = u'ds.daishin.cbpProject Linker.10' # arbitrary string ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid) #윈도우 특성 설정 self.setWindowTitle('CBP Project Linker') # 윈도우 타이틀 지정 선언문 self.setWindowIcon(QIcon("cbplinkericon.png")) self.setGeometry(600, 600, 450, 200) # 윈도우 위치/크기 설정 문법 #self.statusBar().showMessage('ready') idtext = QLabel(self) idtext.text() #idtext.resize(15,15) idtext.setText("Project Path : ") idtext.move(35, 20) pwtext = QLabel(self) pwtext.text() #idtext.resize(15,10) pwtext.setText("Link Impl Path : ") pwtext.move(35, 50) mdtext = QLabel(self) mdtext.text() mdtext.resize(300, 20) mdtext.setText("CBP Project Linker. Made ByJJuN. v1.0") mdtext.move(110, 180) #Project Text Box self.projectbox = QLineEdit(self) self.projectbox.setText("C:\GIT_AREA\cybos_psl") self.projectbox.resize(300, 25) self.projectbox.move(135, 20) #Link Project 용 Text Box self.linkimplbox = QLineEdit(self) self.linkimplbox.setText("C:\GIT_AREA\cybos_cii\CIIImpl") self.linkimplbox.resize(300, 25) self.linkimplbox.move(135, 50) # 버튼1 추가 btn1 = QPushButton('MAKE Link', self) #btn1.resize(btn1.sizeHint()) btn1.move(160, 90) btn1.clicked.connect(self.btnClicked) # 종료 버튼 추가 btnQuit = QPushButton('EXIT', self) btnQuit.move(160, 130) # 종료창 위치/크기 설정 btnQuit.clicked.connect(QCoreApplication.instance().quit) #윈도우 화면 출력 self.show()
def process_signals_for_widget(self, node, widget, signals): """ Process new signals for the OWBaseWidget. """ # This replaces the old OWBaseWidget.processSignals method if sip.isdeleted(widget): log.critical("Widget %r was deleted. Cannot process signals", widget) return app = QCoreApplication.instance() for signal in signals: link = signal.link value = signal.value # Check and update the dynamic link state if link.is_dynamic(): link.dynamic_enabled = can_enable_dynamic(link, value) if not link.dynamic_enabled: # Send None instead value = None handler = link.sink_channel.handler if handler.startswith("self."): handler = handler.split(".", 1)[1] handler = getattr(widget, handler) if link.sink_channel.single: args = (value, ) else: args = (value, signal.id) log.debug("Process signals: calling %s.%s (from %s with id:%s)", type(widget).__name__, handler.__name__, link, signal.id) app.setOverrideCursor(Qt.WaitCursor) try: handler(*args) except Exception: sys.excepthook(*sys.exc_info()) log.exception("Error calling '%s' of '%s'", handler.__name__, node.title) finally: app.restoreOverrideCursor() app.setOverrideCursor(Qt.WaitCursor) try: widget.handleNewSignals() except Exception: sys.excepthook(*sys.exc_info()) log.exception("Error calling 'handleNewSignals()' of '%s'", node.title) finally: app.restoreOverrideCursor()