class VMWidget(QWidget): def __init__(self,parent = None): super(VMWidget,self).__init__(parent) #self.setStyleSheet("QToolTip{background-color:white;color:black;font-size:12px;}") #self.setFont(QFont(u"微软雅黑",12)) self.vmInfoList = [] self.oldVmInfoList = [] self.vmOffInfoList = [] self.threadMap = {} self.processMap = {} self.parent = parent self.domainManager = DomainManager() self.progressMonitor = ProgressThread() self.vmstatusTimer = QTimer() #self.vmstatusTimer.start(7000) self.connect(self.vmstatusTimer, SIGNAL("timeout()"),self.postStatusToServer) self.startVmInfo = None if common.SCROLL_TYPE != "slider": self.scrollArea = QScrollArea(self) self.scrollArea.setStyleSheet("background-color:transparent;border:0px") self.vmButtonList = [] self.vmTableWidget = QTableWidget() self.setTableWidgetStyle() self.mainLayout = QVBoxLayout() self.mainLayout.setMargin(0) self.mainLayout.setSpacing(0) self.mainLayout.addWidget(self.scrollArea) self.mainLayout.addSpacing(10) self.setLayout(self.mainLayout) self.downloadingList = [] if common.SCROLL_TYPE == "slider": #三个自定义button,用于显示相应的虚拟机 self.firstVM = CustomVMButton(self) self.secondVM = CustomVMButton(self) self.thirdVM = CustomVMButton(self) self.vmButtonList = [self.firstVM, self.secondVM, self.thirdVM] for i in range(len(self.vmButtonList)): self.vmButtonList[i].setIcon(QIcon("images/windows.png")) self.vmButtonList[i].setIconSize(QSize(100,100)) self.vmButtonList[i].setFlat(True) self.vmButtonList[i].setFont(QFont("Times", 15, QFont.Bold)) #设置滑动条的样式 self.slider = QSlider(Qt.Vertical,self) self.slider.setStyleSheet( "QSlider::groove:vertical { " "border: 1px solid #4A708B; " "background: #C0C0C0; " "width: 5px; " "border-radius: 1px; " "padding-left:-1px; " "padding-right:-1px; " "padding-top:-1px; " "padding-bottom:-1px; " "}" "QSlider::handle:vertical {" "height: 100px;" "background: white;" "margin: 0 -4px;" "}" ) self.btnLayout = QHBoxLayout(self) self.btnLayout.addStretch() self.btnLayout.addWidget(self.firstVM) self.btnLayout.addWidget(self.secondVM) self.btnLayout.addWidget(self.thirdVM) self.btnLayout.addStretch() self.btnLayout.addSpacing(10) self.btnLayout.addWidget(self.slider) self.btnLayout.setSpacing(10) self.btnLayout.setMargin(10) self.setLayout(self.btnLayout) def setTableWidgetStyle(self): #self.vmTableWidget.setColumnCount(3) #self.vmTableWidget.setRowCount(1) self.vmTableWidget.setFrameShape(QFrame.NoFrame) self.vmTableWidget.setEditTriggers(QTableWidget.NoEditTriggers)#不能编辑 self.vmTableWidget.setSelectionMode(QAbstractItemView.NoSelection) self.vmTableWidget.verticalHeader().setVisible(False)#设置垂直头不可见 self.vmTableWidget.horizontalHeader().setVisible(False)#设置垂直头不可见 self.vmTableWidget.setShowGrid(False) self.vmTableWidget.setFocusPolicy(Qt.NoFocus) self.vmTableWidget.setStyleSheet("QTableWidget{background-color: rgb(235, 235, 235,0);}") def getVmList(self): vmList = [] vmInfo = {} vmInfo["name"] = "15615123021654541" vmInfo["status"] = "offline" vmInfo["name"] = "offline" vmInfo["os_distro"] = "windows_7" vmInfo1 = {} vmInfo1["name"] = "1561545421654541" vmInfo1["status"] = "offline" vmInfo1["name"] = "offline" vmInfo2 = {} vmInfo2["name"] = "1561afew21654541" vmInfo2["status"] = "offline" vmInfo2["name"] = "windows_7" vmInfo3 = {} vmInfo3["name"] = "afewfdsafewfa" vmInfo3["status"] = "offline" vmInfo3["name"] = "windows_7" vmList.append(vmInfo) vmList.append(vmInfo1) vmList.append(vmInfo2) vmList.append(vmInfo3) vmList.append(vmInfo1) vmList.append(vmInfo2) vmList.append(vmInfo3) return vmList def postStatusToServer(self): '''serverState = VMInfoManager.instance().getCurCloudServerState() if serverState != "enable": return''' postInfo = {} state = self.domainManager.getStatus() if self.vmOffInfoList == [] or len(self.downloadingList) != 0: #self.processMap.clear() #self.threadMap.clear() return if len(state) == 0: postInfo["state"] = "shutdown" postInfo["vmname"] = self.vmOffInfoList[0]["vmname"] else: for item in state: postInfo["state"] = "running" if state[item].has_key("disk_io"): postInfo["io_throughput"] = state[item]["disk_io"] if state[item].has_key("max_disk_io"): postInfo["io_throughput_peak"] = state[item]["max_disk_io"] if state[item].has_key("net_io"): postInfo["net_throughput"] = state[item]["net_io"] if state[item].has_key("max_net_io"): postInfo["net_throughput_peak"] = state[item]["max_net_io"] if state[item].has_key("memory_size"): postInfo["memory"] = state[item]["memory_size"]*1024 if state[item].has_key("vmname"): postInfo["vmname"] = state[item]["vmname"] if state[item].has_key("name"): postInfo["coursename"] = state[item]["name"] if state[item].has_key("cpu"): postInfo["cpu_utilization"] = state[item]["cpu"] self.emit(SIGNAL("vmstateinfo"),postInfo) def showVmList(self): subWidget = QWidget() if self.vmstatusTimer.isActive(): pass else: #if globalvariable.CLASS_STATUS: self.vmstatusTimer.start(7000) #self.connect(self.vmstatusTimer, SIGNAL("timeout()"),self.postStatusToServer) if self.scrollArea.widget(): self.scrollArea.takeWidget() self.vmTableWidget = QTableWidget() self.setTableWidgetStyle() #if self.vmTableWidget self.vmTableWidget.clear() #self.vmInfoList = self.getVmList() num = len(self.vmInfoList) columnCount = 1 rowCount = 1 if num == 0: return if num <=3: #self.scrollArea.verticalScrollBar().hide() rowCount = 1 if num == 1: columnCount = 1 elif num == 2: columnCount = 2 elif num == 3: columnCount = 3 else: rowCount = num/3 rest = num%3 if (rowCount == 2 and rest == 0) or rowCount == 1 : pass if rest > 0: rowCount+=1 columnCount = 3 parentWidth = self.parent.width() resolutionValue = StoreInfoParser.instance().getResolutionValue() if resolutionValue: if len(resolutionValue.split("x")) >= 2: parentWidth = int(resolutionValue.split("x")[0])*5/9.0 ratio = parentWidth/800.0 tableWidth = (parentWidth - 20*2 -50*2*ratio)/3 + 5 if len(self.vmInfoList) > 3: tableWidth = (parentWidth - 20*2 -50*2*ratio)/3 - 20*(1 - ratio) + 5 self.vmTableWidget.setColumnCount(columnCount) self.vmTableWidget.setRowCount(rowCount) self.vmTableWidget.setFixedWidth(parentWidth-100) self.vmTableWidget.setFixedHeight((tableWidth+10)*rowCount) self.vmTableWidget.verticalHeader().setDefaultSectionSize(tableWidth+10) self.vmTableWidget.horizontalHeader().setDefaultSectionSize((parentWidth-100)/columnCount) #self.setWidget("status") if columnCount <= 3 and rowCount == 1: for i in range(columnCount): self.setRowColumnWidget(0,i,self.vmInfoList[i]["name"]) else: for i in range(rowCount): for j in range(3): if i*3 + j <= num-1: self.setRowColumnWidget(i, j, self.vmInfoList[i*3+j]["name"]) mainLayout = QHBoxLayout() mainLayout.setMargin(0) mainLayout.addWidget(self.vmTableWidget) subWidget.setLayout(mainLayout) #if self.scrollArea.widget(): #self.scrollArea.takeWidget() self.scrollArea.setWidget(subWidget) self.scrollArea.setWidgetResizable(True) #self.scrollArea.horizontalScrollBar().hide() def setRowColumnWidget(self,row,column,vmid): status = "sfw" #self.vmTableWidget.clear() mainWidget = QWidget() #self.vmTableWidget.hideColumn() #vmRowButtonList = [] parentWidth = self.parent.width() resolutionValue = StoreInfoParser.instance().getResolutionValue() if resolutionValue: if len(resolutionValue.split("x")) >= 2: parentWidth = int(resolutionValue.split("x")[0])*5/9.0 ratio = parentWidth/800.0 vmWidth = (parentWidth - 20*2 -50*2*ratio)/3 if len(self.vmInfoList) > 3: vmWidth = (parentWidth - 20*2 -50*2*ratio)/3 - 20*(1 - ratio) vmButton = CustomVMButton() vmButton.setFixedSize(QSize(vmWidth, vmWidth + 5)) vmButton.setIconSize(QSize(vmWidth - 60*ratio,vmWidth - 30*ratio)) vmButton.setText(self.vmInfoList[row*3 + column]["name"]) vmButton.setFlat(True) vmButton.setFont(QFont("Times", 15, QFont.Bold)) vmInfo = self.vmInfoList[row*3 + column] vmButton.setVMInfo(vmInfo) imageName = "other.png" if self.vmInfoList[row*3 + column].has_key("os_distro"): if common.imageMap.has_key(self.vmInfoList[row*3 + column]["os_distro"]): imageName = common.imageMap[self.vmInfoList[row*3 + column]["os_distro"]] else: LogRecord.instance().logger.info(u'common.imageMap中未找到键值%s' % self.vmInfoList[row*3 + column]["os_distro"]) vmButton.setIcon(QIcon("images/systemImage/%s" % imageName)) # if globalvariable.CLASS_STATUS and not globalvariable.TICHU_STATUS: # self.connect(vmButton, SIGNAL("clicked()"),self.slotOpenVMLesson) # self.connect(vmButton, SIGNAL("controlvm"),self.slotControlVM) # else: # self.connect(vmButton, SIGNAL("clicked()"),self.slotCreateVMLesson) #vmRowButtonList.append(vmButton) self.vmButtonList.append(vmButton) #firMybutton.setStatus("undownload") vmButton.setObjectName(vmid + ":" + QString.number(row) + ":" + QString.number(column)) self.connect(vmButton, SIGNAL("clicked()"),self.startDomain) progressBar = WidgetProgress() progressBar.setFixedSize(vmWidth, vmWidth + 5) #progressBar.progressBar.setValue(0) progressBar.setVmName(self.vmInfoList[row*3 + column]["name"]) progressBar.setObjectName(vmid + ":" + QString.number(row) + ":" + QString.number(column)) #progressBar.objectName() #self.firMybutton.setText(self.tr("确萨")) #progressBar = QProgressBar() myLayout = QHBoxLayout() myLayout.setMargin(0) myLayout.addStretch() myLayout.addWidget(vmButton) myLayout.addWidget(progressBar) myLayout.addStretch() if vmid in self.downloadingList: vmButton.hide() else: progressBar.hide() #firMybutton.hide() mainWidget.setLayout(myLayout) self.vmTableWidget.setCellWidget(row, column, mainWidget) #self.mainLayout.addWidget(mainWidget) def setVMInfoList(self, vmInfoList, vmOffInfoList): self.oldVmInfoList = LocalImgManager.instance().getCompleteList() self.vmInfoList = vmInfoList self.vmOffInfoList = vmOffInfoList self.domainManager.deleteImgList(vmOffInfoList) # needDeleteList = self.compareDelete(self.oldVmInfoList, vmOffInfoList) if self.vmOffInfoList == []: #self.progressMonitor.stop() #self.threadMap.clear() for item in self.processMap: self.processMap[item].stop() if self.processMap[item].isRunning(): self.processMap[item].exit() for item in self.threadMap: if self.threadMap[item].isRunning(): self.threadMap[item].exit() self.processMap.clear() self.threadMap.clear() #self.killRsyncThread() # if len(needDeleteList) == 0: # return # else: # self.domainManager.deleteImgList(needDeleteList) def stopAllDownload(self): for item in self.processMap: self.processMap[item].stop() if self.processMap[item].isRunning(): self.processMap[item].exit() self.killScpThread() for item in self.threadMap: #self.threadMap[item].stop() if self.threadMap[item].isRunning(): self.threadMap[item].exit() self.downloadingList = [] self.processMap.clear() self.threadMap.clear() def killScpThread(self): pidList = self.getScpsProcessId() #sshPidList = self.getSshProcessId() for item in pidList: self.killVmId(item) '''for mtem in sshPidList: self.killVmId(mtem)''' def killVmId(self,killid): cmd = "kill -9 " + killid os.system(str(cmd)) def getScpsProcessId(self):#得到运行虚拟机的进程号序列,可用于关闭某个虚拟机 idList = [] cmd = "ps aux | grep scp" output = "" statusOutput = [] statusOutput = commands.getstatusoutput(cmd) if statusOutput[0] == 0: output = statusOutput[1] else: output = "" result = output.split("\n") for i in range(len(result)): if QString(result[i]).contains("scp"): idList.append(QString(result[i]).simplified().split(" ")[1]) return idList def getSshProcessId(self):#得到运行虚拟机的进程号序列,可用于关闭某个虚拟机 idList = [] cmd = "ps aux | grep /usr/bin/ssh" output = "" statusOutput = [] statusOutput = commands.getstatusoutput(cmd) if statusOutput[0] == 0: output = statusOutput[1] else: output = "" result = output.split("\n") for i in range(len(result)): if QString(result[i]).contains("/usr/bin/ssh"): idList.append(QString(result[i]).simplified().split(" ")[1]) return idList def compareDelete(self,oldList,newList): nameList = [] deleteList = [] for item in newList: nameList.append(item["name"]) for name in oldList: if name not in nameList: deleteList.append(name) return deleteList def autoStartDownload(self): #return num = len(self.vmInfoList) if num == 0: return else: #self.progressMonitor.setVmInfoList(self.vmInfoList) #self.progressMonitor.start() #self.connect(self.progressMonitor, SIGNAL("downloadover"),self.slotDownloadOver) imgMap = LocalImgManager.instance().getCompliteListSize() for i in range(len(self.vmInfoList)): mark = 0 for item in imgMap: if item == self.vmInfoList[i]["name"] and imgMap[item] == self.vmInfoList[i]["img_file_size"]: mark = 1 if mark == 1: continue row = i/3 column = i%3 self.downloadingList.append(self.vmInfoList[i]["name"]) # self.downloadThread = DownloadThread() # self.progressThread = ProgressThread() threadid = self.vmInfoList[i]["name"] + ":" + QString.number(row) + ":" + QString.number(column) # self.downloadThread.setProcessId(threadid + ":" + QString.number(self.vmInfoList[i]["img_file_size"])) # self.progressThread.setProcessId(threadid + ":" + QString.number(self.vmInfoList[i]["img_file_size"])) # self.connect(self.progressThread, SIGNAL("currentprogress"),self.updateProgressBar) # self.connect(self.progressThread, SIGNAL("downloadover"),self.slotDownloadOver) # self.downloadThread.start() # self.progressThread.start() self.setRowColumnWidget(int(row), int(column), self.vmInfoList[i]["name"]) self.createThread(threadid,self.vmInfoList[i]) #time.sleep(1) #return self.startFirstThread() def startFirstThread(self): for item in self.threadMap: self.threadMap[item].start() self.processMap[item].start() self.connect(self.processMap[item], SIGNAL("currentprogress"),self.updateProgressBar) #self.connect(self.processMap[item], SIGNAL("downloadover"),self.slotDownloadOver) self.connect(self.threadMap[item], SIGNAL("downloadover"),self.slotDownloadOver) self.connect(self.threadMap[item], SIGNAL("downloaderror"),self.slotDownloadError) return def slotDownloadError(self,signalid): pass def createThread(self,threadid,vmInfo): if self.threadMap.has_key(threadid): if self.threadMap[threadid].isRunning(): self.threadMap[threadid].exit() self.threadMap.pop(threadid) if self.processMap.has_key(threadid): if self.processMap[threadid].isRunning(): self.processMap[threadid].exit() self.processMap.pop(threadid) downloadThread = DownloadThread() progressThread = ProgressThread() self.threadMap[threadid] = downloadThread self.processMap[threadid] = progressThread self.threadMap[threadid].setProcessId(threadid + ":" + str(vmInfo["img_file_size"])) self.processMap[threadid].setProcessId(threadid + ":" + str(vmInfo["img_file_size"])) #self.threadMap[threadid].start() #self.processMap[threadid].start() #self.connect(self.processMap[threadid], SIGNAL("currentprogress"),self.updateProgressBar) #self.connect(self.processMap[threadid], SIGNAL("downloadover"),self.slotDownloadOver) def checkAddDownload(self): #return num = len(self.vmInfoList) #existImgList = LocalImgManager.instance().getCompleteList() existImgList = LocalImgManager.instance().getCompliteListSize() if num == 0: return else: count = 0 for i in range(len(self.vmInfoList)): row = i/3 column = i%3 if existImgList.has_key(self.vmInfoList[i]["name"]) and existImgList.get(self.vmInfoList[i]["name"]) == self.vmInfoList[i]["img_file_size"]: pass elif self.vmInfoList[i]["name"] in self.downloadingList: pass elif existImgList.has_key(self.vmInfoList[i]["name"]) and self.domainManager.getDom() != None and self.startVmInfo != None and self.startVmInfo == self.domainManager.getDomainInfo(): pass else: if self.vmInfoList[i]["name"] not in self.downloadingList: self.downloadingList.append(self.vmInfoList[i]["name"]) threadid = self.vmInfoList[i]["name"] + ":" + QString.number(row) + ":" + QString.number(column) self.createThread(threadid, self.vmInfoList[i]) self.setRowColumnWidget(int(row), int(column), self.vmInfoList[i]["name"]) count+= 1 if len(self.threadMap) == count: self.startFirstThread() if count > 0: self.emit(SIGNAL("startadddownload")) def startDomain(self): pbp = CustomVMButton().sender() buttonName = pbp.objectName() vmInfo = pbp.vmInfo for item in self.vmOffInfoList: if item["name"] == vmInfo["name"]: self.startVmInfo = item #return vmid = buttonName.split(":")[0] row = buttonName.split(":")[1] column = buttonName.split(":")[2] self.domainManager.setDomainInfo(self.startVmInfo) LogRecord.instance().logger.info(u"开始开启虚拟机-----------------------------------------------00") self.domainManager.startDomainByName() LogRecord.instance().logger.info(u"结束开启虚拟机-----------------------------------------------11") def updateProgressBar(self,count,objectname): #if self.threadMap[objectname].isRunning(): # for i in range(len(self.downloadingList)): # if objectname == self.downloadingList[i]: # progress=self.vmTableWidget.findChild((WidgetProgress, ),objectname) # progress.progressBar.setValue(count) progress=self.vmTableWidget.findChild((WidgetProgress, ),objectname) if not progress: return progress.progressBar.setValue(count) def slotDownloadOver(self,count,name): serverState = VMInfoManager.instance().getCurCloudServerState() if serverState != "enable": return if self.processMap.has_key(name): self.processMap[name].stop() #self.processMap.pop(name) #self.threadMap.pop(name) vmid = name.split(":")[0] row = name.split(":")[1] column = name.split(":")[2] self.downloadingList = [] self.setRowColumnWidget(int(row), int(column), vmid) time.sleep(4) if self.processMap.has_key(name) and self.processMap[name].isRunning: self.processMap[name].exit() if self.threadMap.has_key(name) and self.threadMap[name].isRunning: self.threadMap[name].exit() self.processMap.pop(name) self.threadMap.pop(name) self.emit(SIGNAL("avmdownloadover")) # for item in self.threadMap: # self.threadMap[item].start() # self.processMap[item].start() # self.connect(self.processMap[item], SIGNAL("currentprogress"),self.updateProgressBar) # self.connect(self.processMap[item], SIGNAL("downloadover"),self.slotDownloadOver) # return def getDownloadingList(self): return self.downloadingList def updateVMList(self): 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) if self.vmstatusTimer.isActive(): self.vmstatusTimer.stop() else: pass subWidget = QWidget() vmNum = len(self.vmInfoList) rowNum = 0 subMainLayout = QVBoxLayout() subMainLayout.setMargin(0) #subMainLayout.addStretch() #subMainLayout.addSpacing(10) #subMainLayout.setSpacing(10) self.vmButtonList = [] if vmNum % 3 != 0: rowNum = vmNum / 3 + 1 else: rowNum = vmNum / 3 for i in range(rowNum): indexEnd = 3 if i == rowNum - 1: indexEnd = vmNum - (i*3) parentWidth = self.parent.width() resolutionValue = StoreInfoParser.instance().getResolutionValue() if resolutionValue: if len(resolutionValue.split("x")) >= 2: parentWidth = int(resolutionValue.split("x")[0])*5/9.0 ratio = parentWidth/800.0 vmWidth = (parentWidth - 20*2 -50*2*ratio)/3 if vmNum > 3: vmWidth = (parentWidth - 20*2 -50*2*ratio)/3 - 20*(1 - ratio) vmRowButtonList = [] for j in range(indexEnd): vmButton = CustomVMButton(self) vmButton.setFixedSize(QSize(vmWidth, vmWidth + 5)) vmButton.setIconSize(QSize(vmWidth - 60*ratio,vmWidth - 30*ratio)) vmButton.setText(self.vmInfoList[i*3 + j]["name"]) vmButton.setToolTip(self.tr("course: ") + self.vmInfoList[i*3 + j]["name"]) vmButton.setStyleSheet(u"QToolTip{border-radius:5px;background-color:white;color:black;font-size:20px;font-family:微软雅黑;}") vmButton.setFlat(True) vmButton.setFont(QFont("Times", 15, QFont.Bold)) vmInfo = self.vmInfoList[i*3 + j] vmButton.setVMInfo(vmInfo) imageName = "other.png" if self.vmInfoList[i*3 + j].has_key("os_distro"): if common.imageMap.has_key(self.vmInfoList[i*3 + j]["os_distro"]): imageName = common.imageMap[self.vmInfoList[i*3 + j]["os_distro"]] else: LogRecord.instance().logger.info(u'common.imageMap中未找到键值%s' % self.vmInfoList[i*3 + j]["os_distro"]) vmButton.setIcon(QIcon("images/systemImage/%s" % imageName)) if globalvariable.CLASS_STATUS and not globalvariable.TICHU_STATUS: self.connect(vmButton, SIGNAL("clicked()"),self.slotOpenVMLesson) self.connect(vmButton, SIGNAL("controlvm"),self.slotControlVM) else: self.connect(vmButton, SIGNAL("clicked()"),self.slotCreateVMLesson) vmRowButtonList.append(vmButton) self.vmButtonList.append(vmButton) btnLayout = QHBoxLayout() if vmNum > 3: btnLayout.setSpacing(10) #btnLayout.setMargin(10) btnLayout.addSpacing(30) for vmbtn in vmRowButtonList: btnLayout.addWidget(vmbtn) btnLayout.addStretch() subMainLayout.addLayout(btnLayout) #subMainLayout.addStretch() subWidget.setLayout(subMainLayout) if self.scrollArea.widget(): self.scrollArea.takeWidget() self.scrollArea.setWidgetResizable(False) self.scrollArea.setWidget(subWidget) def startVM(self): return def autoOpenVMLesson(self, vmName, allflag = False): LogRecord.instance().logger.info(u'自动打开相应的虚拟机') if self.vmButtonList: vmInfo = self.vmButtonList[0].getVMInfo() VMOperation.instance().setCurrentVMInfo(vmInfo) #thread.start_new_thread(VMOperation.instance().openVM,()) if allflag == True: if VMOperation.instance().openVM(): LogRecord.instance().logger.info(u'start the lesson') else: if VMOperation.instance().openVM(): LogRecord.instance().logger.info(u'start the lesson') else: LogRecord.instance().logger.info(u'未监测到虚拟机%s的信息' % vmName) def autoOpenOffVMLesson(self): LogRecord.instance().logger.info(u'自动打开相应的虚拟机') if len(self.vmInfoList) == 1: if self.vmInfoList[0]["name"] in self.downloadingList: return else: self.startVmInfo = self.vmInfoList[0] self.domainManager.setDomainInfo(self.startVmInfo) self.domainManager.startDomainByName() else: return def checkDownloadOver(self): if self.autoCourse in self.downloadingList: pass else: self.courseTimer.stop() #self.autoCourse = "" for item in self.vmOffInfoList: if self.autoCourse == item["name"]: vmInfo = item self.domainManager.setDomainInfo(vmInfo) self.domainManager.startDomainByName() return def autoOpenCourse(self,name,classid = None): LogRecord.instance().logger.info(u'自动打开相应的虚拟机') self.autoCourse = name if name in self.downloadingList: self.courseTimer = QTimer() self.courseTimer.start(1000) self.connect(self.courseTimer, SIGNAL("timeout()"),self.checkDownloadOver) else: for item in self.vmOffInfoList: if name == item["name"]: vmInfo = item if classid != None: vmInfo["classid"] = classid self.domainManager.setDomainInfo(vmInfo) self.domainManager.startDomainByName() return def slotCreateVMLesson(self): vmBtn = self.sender() if vmBtn: LogRecord.instance().logger.info(u'开始创建虚拟机') if globalvariable.VM_IS_CREATE_STATUS: LogRecord.instance().logger.info(u'重复点击!') return else: globalvariable.VM_IS_CREATE_STATUS = True LogRecord.instance().logger.info(u'准备获取虚拟机信息!') paramInfo = vmBtn.getVMInfo() LogRecord.instance().logger.info(u'准备获取虚拟机信息完成!') try: vmName = VMOperation.instance().createVMLesson(paramInfo) except: LogRecord.instance().logger.info(u'创建虚拟机异常.........!') LogRecord.instance().logger.info(u'得到创建的虚拟机信息!') if vmName: LogRecord.instance().logger.info(u'创建虚拟机%s成功' % vmName) vmInfo = NetworkManager.instance().getVMInfo(vmName) if vmInfo == None: globalvariable.VM_IS_CREATE_STATUS = False return if len(vmInfo) == 0: globalvariable.VM_IS_CREATE_STATUS = False return vmInfo[0]["vmname"] = vmInfo[0]["name"] if vmInfo: VMOperation.instance().setCurrentVMInfo(vmInfo[0]) if VMOperation.instance().openVM(True): #保存开启虚拟机的名称 #globalvariable.VM_IS_CREATE_STATUS = False WindowMonitor.instance().insertVmId(vmName) else: globalvariable.VM_IS_CREATE_STATUS = False #删除没有成功运行的虚拟机 if VMOperation.instance().removeVMLesson(vmName): LogRecord.instance().logger.info(u"删除后台相应的虚拟机成功") else: LogRecord.instance().logger.info(u'未查询到相应的虚拟机:%s' % vmName) globalvariable.VM_IS_CREATE_STATUS = False else: LogRecord.instance().logger.info(u'创建虚拟机失败') globalvariable.VM_IS_CREATE_STATUS = False #刷新虚拟机界面 self.emit(SIGNAL("refreshVMS")) def slotControlVM(self, action): vmBtn = self.sender() if vmBtn: vmInfo = vmBtn.getVMInfo() VMOperation.instance().setCurrentVMInfo(vmInfo) VMOperation.instance().controlVM(action) vmInfos = globalvariable.VM_INFO self.setVMInfoList(vmInfos,[]) self.updateVMList() def slotOpenVMLesson(self): #vmInfo = [] vmBtn = self.sender() if vmBtn: btnVMInfo = vmBtn.getVMInfo() VMOperation.instance().setCurrentVMInfo(btnVMInfo) VMOperation.instance().openVM(True) # if globalvariable.CLASS_STATUS: # vmInfo = globalvariable.VM_INFO # else: # vmInfo = VMInfoManager.instance().getLessonListInfo() # #self.setVMInfoList(vmInfo,[]) #self.updateVMList() #slider def setSliderMaxValue(self, value): """设在滑动条的最大值""" maxValue = 1 if value % 3 == 0: maxValue = (value / 3) else: maxValue = (value / 3 + 1) maxValue = maxValue - 1 self.slider.setMinimum(1) self.slider.setMaximum(maxValue*3) self.slider.setValue(self.slider.maximum()) self.currentIndex = maxValue self.maxValue = maxValue self.updateVMList() def paintEvent(self,event): if common.SCROLL_TYPE == "slider": self.setNodeSize(QSize(self.geometry().width()*4/15,self.geometry().height()*4/9)) elif len(self.vmInfoList) <= 6: subWidget = self.scrollArea.widget() if subWidget != None: if len(self.vmInfoList) <= 3: subWidget.move((self.geometry().width() - subWidget.width())/2, (self.geometry().height() - subWidget.height())/2 - 20) else: subWidget.move((self.geometry().width() - subWidget.width())/2 - 15, (self.geometry().height() - subWidget.height())/2) QWidget.paintEvent(self, event) #slider def setNodeSize(self,size): self.btnLayout.setSpacing(size.width()/20) self.btnLayout.setMargin(size.width()*3/20) self.firstVM.setIconSize(size) self.secondVM.setIconSize(size) self.thirdVM.setIconSize(size) self.slider.resize(QSize(self.slider.frameGeometry().width(),self.height()-100)) def wheelEvent(self,event): """鼠标滚轮滚动事件,显示对应的虚拟机""" if common.SCROLL_TYPE == "slider": if event.delta() < 0 and self.currentIndex > 0: self.currentIndex -= 1 self.updateVMListSlider() elif event.delta() > 0 and self.currentIndex < self.maxValue: self.currentIndex += 1 self.updateVMListSlider() self.slider.wheelEvent(event) else: maxValue = self.scrollArea.verticalScrollBar().maximum() minValue = self.scrollArea.verticalScrollBar().minimum() currentValue = self.scrollArea.verticalScrollBar().value() if event.delta() < 0 and currentValue < maxValue: self.scrollArea.wheelEvent(event) elif event.delta() > 0 and currentValue > minValue: self.scrollArea.wheelEvent(event) #slider def updateVMListSlider(self): """更新虚拟机列表""" for i in range(len(self.vmButtonList)): self.vmButtonList[i].hide() vmsInfoList = VMInfoManager.instance().getVMSInfo() if vmsInfoList: self.slider.show() startIndex = (self.maxValue - self.currentIndex) * 3 if startIndex/3 == (self.maxValue): endIndex = len(vmsInfoList) else: endIndex = startIndex + 3 for i in range(startIndex, endIndex): self.vmButtonList[i - startIndex].setText(vmsInfoList[i]) self.vmButtonList[i - startIndex].show() else: self.slider.hide() """ echo <graphics type='sdl display='$DISPLAY' xauth='$XAUTHORITY'/>
def add_slider(self, label, description, minimum, maximum, value, slider_moved_func, parent, tick_interval=1, single_step=1, slider_scale_factor=1, int_values=False): # make layout to hold slider and textbox control_layout = QHBoxLayout() slider_label = label + "_slider" textbox_label = label + "_textbox" # make slider & add to layout slider = QSlider(Qt.Horizontal) slider.setObjectName(label) slider.setFocusPolicy(Qt.StrongFocus) slider.setTickPosition(QSlider.TicksBothSides) slider.setTickInterval(tick_interval) slider.setSingleStep(single_step) slider.setMinimum(minimum) slider.setMaximum(maximum) slider.setValue(value) control_layout.addWidget(slider) # make textbox & add to layout textbox = QLineEdit() textbox.setObjectName(label) textbox.setFixedWidth(40) textbox.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) textbox.returnPressed.connect( self.controller.update_crop_params_from_gui) self.update_textbox_from_slider(slider, textbox, slider_scale_factor, int_values) control_layout.addWidget(textbox) # connect slider to set textbox text & update params slider.sliderMoved.connect(lambda: self.update_textbox_from_slider( slider, textbox, slider_scale_factor, int_values)) slider.sliderMoved.connect(slider_moved_func) slider.sliderPressed.connect(lambda: self.slider_pressed(slider)) slider.sliderReleased.connect(lambda: self.slider_released(slider)) # connect textbox to textbox.editingFinished.connect( lambda: self.update_slider_from_textbox(slider, textbox, slider_scale_factor)) textbox.editingFinished.connect(slider_moved_func) # add row to form layout parent.addRow(description, control_layout) # add to list of controls self.crop_param_controls[-1][slider_label] = slider self.crop_param_controls[-1][textbox_label] = textbox
class Slider(QWidget): def __init__(self, caption, default_value, minimum_value=1, maximum_value=60, single_step=1, page_step=6, caption_size=None, unit='', time=False, tooltip=''): QWidget.__init__(self) self.value = default_value self.unit = unit self.time = time description = QLabel(caption) description.setWordWrap(True) description.setToolTip(tooltip) if caption_size: description.setMaximumWidth(caption_size) self.slider = QSlider(Qt.Horizontal) self.slider.setMaximum(maximum_value) self.slider.setMinimum(minimum_value) self.slider.setSingleStep(single_step) self.slider.setPageStep(page_step) self.slider.setToolTip(tooltip) #self.slider.setTickInterval(2) #self.slider.setTickPosition(QSlider.TicksBelow) self.slider.valueChanged.connect(self.__on_change) self.value_label = QLabel() hbox = QHBoxLayout() hbox.addWidget(description) hbox.addWidget(self.slider) hbox.addWidget(self.value_label) hbox.setMargin(0) self.setLayout(hbox) self.setContentsMargins(5, 0, 5, 0) self.slider.setValue(self.value) self.__on_change(self.value) def __on_change(self, value): # FIXME: Fill with spaces to reach the maximum length self.value = value unit = self.unit if self.time: minutes = timedelta(minutes=self.value) date = datetime(1, 1, 1) + minutes text = "%02dh %02dm" % (date.hour, date.minute) else: text = "%s %s" % (self.value, self.unit) self.value_label.setText(text) def get_value(self): return int(self.slider.value())
def __init__(self): super(PyGui, self).__init__() self.setObjectName('PyGui') self.pub = rospy.Publisher("pyqt_topic", String, queue_size=10) rospy.init_node('pyqt_gui') self.current_value = 0 my_layout = QHBoxLayout() my_btn = QPushButton() my_btn.setText("Publisher") my_btn.setFixedWidth(130) my_btn.clicked.connect(self.publish_topic) my_layout.addWidget(my_btn) my_layout.addSpacing(50) self.my_label = QLabel() self.my_label.setFixedWidth(140) self.my_label.setText("num: " + str(0)) self.my_label.setEnabled(False) my_layout.addWidget(self.my_label) my_slider = QSlider() my_slider.setMinimum(0) my_slider.setMaximum(99) my_slider.setOrientation(Qt.Horizontal) my_slider.valueChanged.connect(self.changeValue) my_vlay = QVBoxLayout() my_vlay.addWidget(my_slider) layout = QVBoxLayout() layout.addLayout(my_layout) layout.addLayout(my_vlay) self.setLayout(layout)
def getSlider(self, parent): sld = QSlider(parent) sld.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum) sld.setMinimum(0) sld.setMaximum(99) sld.setPageStep(10) sld.setPageStep(10) sld.setMinimumHeight(50) sld.setTickInterval(25) sld.setTickPosition(QSlider.TicksBothSides) return sld
def initUI(self): """Initialize ROS node.""" self.setGeometry(300, 300, 500, 300) self.setWindowTitle('RDDA_GUI') btnRun = QPushButton('Run') btnRun.setFixedWidth(150) self.btnCls = QPushButton('Stop') self.btnCls.setFixedWidth(150) sldPos = QSlider() sldPos.setOrientation(Qt.Horizontal) sldPos.setMinimum(0) sldPos.setMaximum(100) sldStf = QSlider() sldStf.setOrientation(Qt.Horizontal) sldStf.setMinimum(0) sldStf.setMaximum(100) self.labelPos = QLabel() self.labelPos.setFixedWidth(200) self.labelPos.setText("Position: " + str(0)) self.labelStf = QLabel() self.labelStf.setFixedWidth(200) self.labelStf.setText("Stiffness: " + str(0)) hboxBtn = QHBoxLayout() hboxBtn.addStretch(1) hboxBtn.addWidget(btnRun) hboxBtn.addSpacing(20) hboxBtn.addWidget(self.btnCls) hboxPos = QHBoxLayout() hboxPos.addWidget(sldPos) hboxPos.addSpacing(50) hboxPos.addWidget(self.labelPos) hboxStf = QHBoxLayout() hboxStf.addWidget(sldStf) hboxStf.addSpacing(50) hboxStf.addWidget(self.labelStf) layout = QVBoxLayout() layout.addLayout(hboxPos) layout.addLayout(hboxStf) layout.addLayout(hboxBtn) self.setLayout(layout) # self.rosThread = RosThread(self.joint_cmds) self.rosThread = RosThread() btnRun.clicked.connect(self.start_ros) self.btnCls.clicked.connect(self.rosThread.stop) sldPos.valueChanged.connect(self.set_pos) sldStf.valueChanged.connect(self.set_stf)
def _addSlider(self, v, cnt): control = QSlider(Qt.Horizontal) control.setMinimumWidth(172) control.setFocusPolicy(Qt.StrongFocus) control.setMaximum(v.max * 160) control.setMinimum(v.min * 160) control.setValue(v.value * 160) control.tag = cnt if self.styleName == "mac": control.setAttribute(Qt.WA_MacMiniSize, True) self.layout.addWidget(control, cnt, 1) self.connect(control, SIGNAL("valueChanged(int)"), self.numberChanged_)
class ConfigWidget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) layout = QFormLayout() self.setLayout(layout) self.inputLabel = QLabel("Video Input") self.inputLayout = QHBoxLayout() self.inputCombobox = QComboBox() self.inputSettingsToolButton = QToolButton() self.inputSettingsToolButton.setText("Settings") configIcon = QIcon.fromTheme("preferences-other") self.inputSettingsToolButton.setIcon(configIcon) self.inputSettingsToolButton.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum) self.inputSettingsToolButton.setToolButtonStyle(Qt.ToolButtonIconOnly) self.inputSettingsStack = QStackedWidget() blankWidget = QWidget() self.inputSettingsStack.addWidget(blankWidget) self.inputSettingsStack.addWidget(self.inputSettingsToolButton) self.inputLayout.addWidget(self.inputCombobox) self.inputLayout.addWidget(self.inputSettingsStack) layout.addRow(self.inputLabel, self.inputLayout) self.videocolourLabel = QLabel(self.tr("Colour Format")) self.videocolourComboBox = QComboBox() self.videocolourComboBox.addItem("video/x-raw-rgb") self.videocolourComboBox.addItem("video/x-raw-yuv") self.videocolourComboBox.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Maximum) layout.addRow(self.videocolourLabel, self.videocolourComboBox) self.framerateLabel = QLabel("Framerate") self.framerateLayout = QHBoxLayout() self.framerateSlider = QSlider() self.framerateSlider.setOrientation(Qt.Horizontal) self.framerateSlider.setMinimum(1) self.framerateSlider.setMaximum(60) self.framerateSpinBox = QSpinBox() self.framerateSpinBox.setMinimum(1) self.framerateSpinBox.setMaximum(60) self.framerateLayout.addWidget(self.framerateSlider) self.framerateLayout.addWidget(self.framerateSpinBox) layout.addRow(self.framerateLabel, self.framerateLayout) self.videoscaleLabel = QLabel("Video Scale") self.videoscaleComboBox = QComboBox() for scale in resmap: self.videoscaleComboBox.addItem(scale) self.videoscaleComboBox.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Maximum) layout.addRow(self.videoscaleLabel, self.videoscaleComboBox)
def __init__(self): QWidget.__init__(self) self.resize(400, 100) self.setWindowTitle('Control Duty Cycle of PWM0') sl = QSlider(Qt.Horizontal) sl.setMinimum(0) sl.setMaximum(65535) sl.setValue(0) sl.valueChanged.connect(self.set_pwm) layout = QVBoxLayout() layout.addWidget(sl) self.setLayout(layout) self.init_pwm()
def __init__(self): QWidget.__init__(self) self.resize(400, 100) self.setWindowTitle('Control Duty Cycle of PWM0') sl = QSlider(Qt.Horizontal) sl.setMinimum(0) sl.setMaximum(255) sl.setValue(128) sl.valueChanged.connect(self.set_pwm) layout = QVBoxLayout() layout.addWidget(sl) self.setLayout(layout) self.init_pwm()
class LabelControlItems(QWidget): def __init__(self): super(LabelControlItems, self).__init__() nlabels = 5 self.combobox_labels = QComboBox() self.label_label = QLabel("Label: ") self.label_text = QLabel("Text: ") self.text_label = QLineEdit("Label1") self.button_label = QPushButton("On/Off") self.scale_labelsize = QSlider(Qt.Horizontal) self.label_labelsize = QLabel("Label Size") self.scale_labelsize.setMinimum(1) self.scale_labelsize.setValue(20) self.button_label.setCheckable(True) for i in range(nlabels): self.combobox_labels.addItem("Label"+str(i+1)) layout = QGridLayout() layout.addWidget(self.label_label,0,0) layout.addWidget(self.combobox_labels,1,0) layout.addWidget(self.label_text,0,1) layout.addWidget(self.text_label,1,1) layout.addWidget(self.button_label,1,2) layout.addWidget(self.label_labelsize,0,3) layout.addWidget(self.scale_labelsize,1,3) for col, stretch in enumerate((5,5,5,5)): layout.setColumnStretch(col, stretch) layout.setMargin(5) layout.setHorizontalSpacing(5) layout.setVerticalSpacing(0) self.setLayout(layout)
class okno_podzialu(QDialog): def __init__(self, value=0, parent=None): super(okno_podzialu, self).__init__(parent) self.aa = str(value) self.setWindowTitle("Divide Ringwidth") self.resize(150, 80) self.s = QSlider(Qt.Horizontal) self.s.setMinimum(1) self.s.setMaximum(int(self.aa)) self.wart1 = QLabel("1") self.wart2 = QLabel(self.aa) self.lab = QLabel("Length = " + self.aa + " [1/100mm]") self.ok = QPushButton("OK") self.anuluj = QPushButton("Anuluj") layout = QGridLayout() layout.addWidget(self.wart1, 0, 0) layout.addWidget(self.s, 0, 1) layout.addWidget(self.wart2, 0, 2) layout.addWidget(self.lab, 1, 0, 1, 3) layout1 = QHBoxLayout() layout1.addWidget(self.ok) layout1.addWidget(self.anuluj) layout.addLayout(layout1, 2, 0, 1, 3) self.setLayout(layout) self.connect(self.s, SIGNAL("valueChanged(int)"), self.uaktualnij) self.connect(self.anuluj, SIGNAL("clicked()"), self.anulowanie) self.connect(self.ok, SIGNAL("clicked()"), self.akceptuj) def uaktualnij(self): self.wart1.setText(str(self.s.value())) self.wart2.setText(str(int(self.aa) - self.s.value())) def akceptuj(self): self.val0 = self.s.value() self.val1 = int(self.aa) - self.s.value() self.hide() def anulowanie(self): self.close()
def setMinimum(self, val): QSlider.setMinimum(self, val * 100)
class Window(QMainWindow): def __init__(self,parent = None): QMainWindow.__init__(self,parent) self.setObjectName("self") self.resize(758, 673) self.setWindowTitle("Sabel") self.setWindowIcon(Icons.sabel) self.centralwidget = QWidget(self) self.centralwidget.setObjectName("centralwidget") self.horizontalLayout = QHBoxLayout(self.centralwidget) self.horizontalLayout.setObjectName("horizontalLayout") self.horizontalLayout.setMargin(0) self.styleIndex = styleIndex #TabWidgets self.tab_1 = QWidget(self) self.tab_1.setObjectName("tab_1") self.tab_1.setMinimumWidth(800) self.tabWidget = Tab(self.tab_1) self.tabWidget.setObjectName("tabWidget") self.VericalLayout = QVBoxLayout(self.tab_1) self.VericalLayout.setMargin(0) self.VericalLayout.setObjectName("VericalLayout") self.VericalLayout.addWidget(self.tabWidget) self.tabWidget_2 = QTabWidget(self) #self.tabWidget_2.setMaximumWidth(200) self.tabWidget_2.setObjectName("tabWidget_2") self.tabWidget_3 = QTabWidget(self) self.tabWidget_3.setMaximumHeight(260) self.tabWidget_3.setObjectName("tabWidget_3") #Tree self.tab_5 = QWidget() self.tab_5.setObjectName("tab_5") #self.tab_5.setMaximumWidth(200) self.VerticalLayout_2 = QVBoxLayout(self.tab_5)#QHBoxLayout(self.tab_5) self.VerticalLayout_2.setMargin(0) self.VerticalLayout_2.setObjectName("horizontalLayout_3") self.treeWidget = Tree(self.tab_5) self.treeWidget.setObjectName("treeWidget") self.treeWidget.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn) self.treeWidget.horizontalScrollBar().show() self.treebar = QToolBar() action_Folder = QAction(Icons.newfolder,'New Folder', self) action_Folder.triggered.connect(self.about) action_Android = QAction(Icons.android,'Android', self) action_Android.triggered.connect(self.android) action_Ant = QAction(Icons.ant_view,'Ant', self) action_Ant.triggered.connect(self.ant) self.treebar.addAction(action_Folder) self.treebar.addAction(action_Android) self.treebar.addAction(action_Ant) self.treebar.setIconSize(QSize(16,16)) self.VerticalLayout_2.addWidget(self.treebar) self.VerticalLayout_2.addWidget(self.treeWidget) #Outline self.tab_2 = QWidget() self.tab_2.setObjectName("tab_2") #self.tab_2.setMaximumWidth(200) self.VerticalLayout_3 = QVBoxLayout(self.tab_2) self.VerticalLayout_3.setMargin(0) self.VerticalLayout_3.setObjectName("VerticalLayout_3") self.outlineWidget = Tree(self.tab_2) self.outlineWidget.setObjectName("outlineWidget") self.VerticalLayout_3.addWidget(self.outlineWidget) #Output self.tab_6 = QWidget() self.tab_6.setObjectName("tab_6") #GGGGGGGGGGGGGGGGGGGG AWESOME self.horizontalLayout_2 = QVBoxLayout(self.tab_6) self.horizontalLayout_2.setMargin(0) self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.textEdit = QTextEdit(self.tab_6) self.textEdit.setObjectName("textEdit") self.lineeEdit = QLineEdit(self.tab_6) self.lineeEdit.setObjectName("lineeEdit") self.label = QLabel(self.tab_6) self.label.setText("Input:") self.horizontalLayout_2.addWidget(self.textEdit) self.horizontalLayout_2.addWidget(self.label) self.horizontalLayout_2.addWidget(self.lineeEdit) #Error self.tab_7 = QWidget() self.tab_7.setObjectName("tab_7") self.horizontalLayout_4 = QHBoxLayout(self.tab_7) self.horizontalLayout_4.setMargin(0) self.horizontalLayout_4.setObjectName("horizontalLayout_4") self.textEdit_2 = QTextEdit(self.tab_7) self.textEdit_2.setObjectName("textEdit_2") self.horizontalLayout_4.addWidget(self.textEdit_2) #Find self.tab_8 = QWidget() self.tab_8.setObjectName("tab_8") self.horizontalLayout_5 = QHBoxLayout(self.tab_8) self.horizontalLayout_5.setObjectName("horizontalLayout_5") self.lineEdit = QLineEdit(self.tab_8) self.lineEdit.setObjectName("lineEdit") self.lineEdit_2 = QLineEdit(self.tab_8) self.lineEdit_2.setObjectName("lineEdit_2") self.findClose = QPushButton(self.tab_8) self.findClose.setIcon(Icons.close_view) self.findClose.setFlat(True) self.findClose.clicked.connect(self.findBarShow) self.find = QPushButton(self.tab_8) self.find.setText("Find") self.find.clicked.connect(self.findCurrentText) self.replacefind = QPushButton(self.tab_8) self.replacefind.setText("Replace/Find") self.replace = QPushButton(self.tab_8) self.replace.setText("Replace") self.replace.clicked.connect(self.replaceCurrentText) self.replaceAll = QPushButton(self.tab_8) self.replaceAll.setText("Replace All") self.replaceAll.clicked.connect(self.replaceAllText) self.caseSensitive = QToolButton(self.tab_8) self.caseSensitive.setText("cs") self.caseSensitive.setCheckable(True) self.wholeWord = QToolButton(self.tab_8) self.wholeWord.setText("ww") self.wholeWord.setCheckable(True) self.regex = QToolButton(self.tab_8) self.regex.setText("re") self.regex.setCheckable(True) self.backward = QToolButton(self.tab_8) self.backward.setText("bk") self.backward.setCheckable(True) self.backward.setDisabled(True) self.horizontalLayout_5.addWidget(self.findClose) self.horizontalLayout_5.addWidget(self.find) self.horizontalLayout_5.addWidget(self.lineEdit) self.horizontalLayout_5.addWidget(self.lineEdit_2) self.horizontalLayout_5.addWidget(self.caseSensitive) self.horizontalLayout_5.addWidget(self.wholeWord) self.horizontalLayout_5.addWidget(self.regex) self.horizontalLayout_5.addWidget(self.backward) self.horizontalLayout_5.addWidget(self.replacefind) self.horizontalLayout_5.addWidget(self.replace) self.horizontalLayout_5.addWidget(self.replaceAll) self.horizontalLayout_5.setMargin(0) self.tab_8.setMaximumHeight(25) self.VericalLayout.addWidget(self.tab_8) self.tab_8.hide() self.tabWidget_2.addTab(self.tab_5,"Projects") self.tabWidget_2.addTab(self.tab_2,"Outline") self.tabWidget_3.addTab(self.tab_7,"Error") self.tabWidget_3.addTab(self.tab_6,"Output") self.tabWidget_3.setTabIcon(0,Icons.error) self.tabWidget_3.setTabIcon(1,Icons.console_view) self.tabWidget.setTabsClosable(True) self.tabWidget.setTabShape(0) #Splitters self.split1 = QSplitter(Qt.Horizontal) self.split1.addWidget(self.tabWidget_2) self.split1.addWidget(self.tab_1) #self.split1.addWidget(self.tab_5) self.split2 = QSplitter(Qt.Vertical) self.split2.addWidget(self.split1) self.split2.addWidget(self.tabWidget_3) self.tabWidget_3.hide() self.horizontalLayout.addWidget(self.split2) #Status self.statusbar = QStatusBar(self) self.statusbar.setObjectName("statusbar") self.aboutButton = QPushButton(self) self.aboutButton.setFlat(True) self.aboutButton.setIcon(Icons.anchor) self.aboutButton.clicked.connect(self.about) self.cmdButton = QPushButton(self) self.cmdButton.setFlat(True) self.cmdButton.setIcon(Icons.console_view) self.cmdButton.clicked.connect(self.cmd) self.cmdButton.setShortcut('Ctrl+O') self.findButton = QPushButton(self) self.findButton.setFlat(True) self.findButton.setIcon(Icons.find) self.findButton.setShortcut("Ctrl+F") self.findButton.clicked.connect(self.findBarShow) self.zoominButton = QPushButton(self) self.zoominButton.setFlat(True) self.zoominButton.setIcon(Icons.zoomplus) self.zoominButton.clicked.connect(self.zoomin) self.zoomoutButton = QPushButton(self) self.zoomoutButton.setFlat(True) self.zoomoutButton.setIcon(Icons.zoomminus) self.zoomoutButton.clicked.connect(self.zoomout) self.fontButton = QPushButton(self) self.fontButton.setFlat(True) self.fontButton.setIcon(Icons.font) self.fontButton.clicked.connect(self.setFont) self.statusbar.addWidget(self.aboutButton) self.statusbar.addWidget(self.cmdButton) self.statusbar.addWidget(self.findButton) self.statusbar.addWidget(self.zoominButton) self.statusbar.addWidget(self.zoomoutButton) self.statusbar.addWidget(self.fontButton) #self.statusbar.setFixedHeight(18) #Init colorstyling self.colorStyle = None self.initColorStyle() #Init self.setCentralWidget(self.centralwidget) self.setStatusBar(self.statusbar) self.textEdit.setReadOnly(True) self.fontName = fontName #QtGui.QApplication.setStyle(QtGui.QStyleFactory.create('Cleanlooks')) def findBarShow(self): if(self.tab_8.isHidden()): self.tab_8.show() else: self.tab_8.hide() def initToolBar(self): self.action_NewProject = QAction(Icons.newprj, 'Project', self) self.action_NewProject.setShortcut('Ctrl+P') self.action_NewProject.triggered.connect(self.newProject) self.action_NewProject.setToolTip("Create a New Project") self.action_NewProject.setStatusTip("Create a New Project") self.action_Open = QAction(Icons.open, 'Open', self) self.action_Open.setShortcut('Ctrl+O') self.action_Open.triggered.connect(self.fileOpen) self.action_Open.setToolTip("Open File") self.action_Open.setStatusTip("Open File") self.action_Save = QAction(Icons.save, 'Save', self) self.action_Save.setShortcut('Ctrl+S') self.action_Save.triggered.connect(self.fileSave) self.action_Save.setToolTip("Save Current File") self.action_SaveAll = QAction(Icons.saveall, 'SaveAll', self) self.action_SaveAll.setShortcut('Ctrl+A') self.action_SaveAll.triggered.connect(self.fileSaveAll) self.action_SaveAll.setToolTip("Save All Files") self.action_Help = QAction(Icons.toc_open, 'Help', self) self.action_Help.triggered.connect(self.help) self.action_Run = QAction(Icons.run, 'Run', self) self.action_Run.setShortcut('Ctrl+R') self.action_Run.triggered.connect(self.adb.run) self.action_RunFile = QAction(Icons.go, 'File', self) self.action_RunFile.triggered.connect(self.command.setCmd) self.lineeEdit.returnPressed.connect(self.command.setCmdLine) self.action_Stop = QAction(Icons.stop, 'Stop', self) self.action_Stop.setShortcut('Ctrl+Q') self.action_Stop.triggered.connect(self.adb.stop) self.action_Design = QAction(Icons.task_set, 'Design', self) self.action_Todo = QAction(Icons.task_set, 'Todo', self) #self.action_Todo.triggered.connect(self.stop) #Only variation CHeck Later men = QMenu() self.threshSlider = QSlider() self.threshSlider.setTickPosition(QSlider.TicksLeft) self.threshSlider.setOrientation(Qt.Horizontal) self.threshSlider.setValue(threshold) self.threshSlider.setMinimum(0) self.threshSlider.setMaximum(5) self.threshSlider.valueChanged.connect(self.setThreshold) #self.threshSlider.setInvertedAppearance(True) self.threshSliderAction = QWidgetAction(men) self.threshSliderAction.setDefaultWidget(self.threshSlider) men.addAction(QAction("Ident",self)) men.addAction(QAction("Edit",self)) men.addAction(QAction("Paste",self)) men.addAction(QAction("Tabs",self)) men.addSeparator() men.addAction(QAction("Threshold",self)) men.addAction(self.threshSliderAction) self.action_Options = QAction(Icons.thread_view, 'Options', self) self.action_Options.setMenu(men) self.action_Options.triggered.connect(self.options) self.action_Full = QAction(Icons.fullscreen, 'Full', self) self.action_Full.setShortcut('Shift+Enter') self.action_Full.triggered.connect(self.full) self.action_Style = QAction(Icons.style, 'Style', self) men1 = QMenu() self.styleslist = [] self.style1 = QAction("All Hallow's Eve",self) self.style1.triggered.connect(lambda:self.style_clicked(1)) self.style1.setCheckable(True) self.style2 = QAction("Amy",self) self.style2.triggered.connect(lambda:self.style_clicked(2)) self.style2.setCheckable(True) self.style3 = QAction("Aptana Studio",self) self.style3.triggered.connect(lambda:self.style_clicked(3)) self.style3.setCheckable(True) self.style4 = QAction("Bespin",self) self.style4.triggered.connect(lambda:self.style_clicked(4)) self.style4.setCheckable(True) self.style5 = QAction("Blackboard",self) self.style5.triggered.connect(lambda:self.style_clicked(5)) self.style5.setCheckable(True) self.style6 = QAction("Choco",self) self.style6.triggered.connect(lambda:self.style_clicked(6)) self.style6.setCheckable(True) self.style7 = QAction("Cobalt",self) self.style7.triggered.connect(lambda:self.style_clicked(7)) self.style7.setCheckable(True) self.style8 = QAction("Dawn",self) self.style8.triggered.connect(lambda:self.style_clicked(8)) self.style8.setCheckable(True) self.style9 = QAction("Eclipse",self) self.style9.triggered.connect(lambda:self.style_clicked(9)) self.style9.setCheckable(True) self.styleslist.append(self.style1) self.styleslist.append(self.style2) self.styleslist.append(self.style3) self.styleslist.append(self.style4) self.styleslist.append(self.style5) self.styleslist.append(self.style6) self.styleslist.append(self.style7) self.styleslist.append(self.style8) self.styleslist.append(self.style9) men1.addActions(self.styleslist) self.action_Style.setMenu(men1) self.styleslist[self.styleIndex].setChecked(True) self.action_Stop.setDisabled(True) self.toolbar = self.addToolBar('ToolBar') self.toolbar.setIconSize(QSize(16,16)) self.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) self.toolbar.setAllowedAreas(Qt.AllToolBarAreas) #self.toolbar.setFixedHeight(40) self.toolbar.addAction(self.action_NewProject) self.toolbar.addAction(self.action_Open) self.toolbar.addAction(self.action_Save) self.toolbar.addAction(self.action_SaveAll) self.toolbar.addSeparator() self.toolbar.addAction(self.action_Run) self.toolbar.addAction(self.action_RunFile) self.toolbar.addAction(self.action_Stop) self.toolbar.addSeparator() self.toolbar.addAction(self.action_Design) self.toolbar.addAction(self.action_Todo) self.toolbar.addAction(self.action_Options) self.toolbar.addAction(self.action_Style) self.toolbar.addSeparator() self.toolbar.addAction(self.action_Help) self.toolbar.addAction(self.action_Full) def about(self): QMessageBox.about(self, "About Sabel IDE", """ <b>Sabel</b> v%s <p> All rights reserved in accordance with GPL v3 or later. <p>This application can be used for Squirrel and EmoFramework Projects. <p>Squirrel Shell Copyright (c) 2006-2011, Constantin Makshin <p>Squirrel Copyright (c) Alberto Demichelis <p>zlib Copyright (c) Jean-loup Gailly and Mark Adler <p>Icons Copyright (c) Eclipse EPL <p>Emo-Framework Copyright (c) 2011 Kota Iguchi <p>Python %s - Qt %s - PyQt %s on %s <p>Created By: pyros2097 <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ % ( __version__,PY_VERSION, QT_VERSION_STR, PYQT_VERSION_STR,OS_NAME)) def help(self): QMessageBox.about(self, "About Simple Editor","This is The Help") def full(self): if not self.isFull: self.setWindowState(Qt.WindowFullScreen) self.isFull = True else: self.setWindowState(Qt.WindowMaximized) self.isFull = False def android(self): form = DialogAndroid(self) form.show() def ant(self): pass def cmd(self): if(self.tabWidget_3.isHidden()): self.tabWidget_3.show() else: self.tabWidget_3.hide() def findCurrentText(self): edt = self.tabWidget.widget(self.tabWidget.currentIndex()) edt.findText(self.lineEdit.text(),self.regex.isChecked(),self.caseSensitive.isChecked(),self.wholeWord.isChecked(),self.backward.isChecked()) def replaceCurrentText(self): edt = self.tabWidget.widget(self.tabWidget.currentIndex()) done = edt.findText(self.lineEdit.text(),self.regex.isChecked(),self.caseSensitive.isChecked(),self.wholeWord.isChecked(),self.backward.isChecked()) if(done): edt.replaceText(self.lineEdit_2.text()) else: QMessageBox.about(self, "About Sabel IDE","Could Not Find Text") return done def replaceAllText(self): edt = self.tabWidget.widget(self.tabWidget.currentIndex()) while(edt.findText(self.lineEdit.text(),self.regex.isChecked(),self.caseSensitive.isChecked(),self.wholeWord.isChecked(),self.backward.isChecked())): edt.replaceText(self.lineEdit_2.text()) def zoomin(self): for i in range(len(self.files)): self.tabWidget.widget(i).zoomin() def zoomout(self): for i in range(len(self.files)): self.tabWidget.widget(i).zoomout() def setFont(self): font = QFont() font.setFamily(self.fontName) fdialog = QFontDialog(self) fdialog.show() fdialog.setCurrentFont(font) fdialog.accepted.connect(lambda:self.setFontName(fdialog.currentFont())) def setFontName(self,font): #print "accepted" #print font.family() self.fontName = str(font.family()) config.setFontName(self.fontName) for i in range(len(self.files)): self.tabWidget.widget(i).setFontName(self.fontName) def setThreshold(self,val): config.setThresh(val) for i in range(len(self.files)): self.tabWidget.widget(i).setThreshold(val) def initColorStyle(self): self.colorStyle = Styles[self.styleIndex] pal = QPalette(self.tabWidget_2.palette()) #print pal.color(QPalette.Base).name() #print pal.color(QPalette.Window).name() pal.setColor(QPalette.Base,self.colorStyle.paper) pal.setColor(QPalette.Text,self.colorStyle.color) self.tabWidget_2.setPalette(pal) self.tabWidget_3.setPalette(pal) def style_clicked(self,no): self.styleIndex = no -1 #print self.styleIndex for i in self.styleslist: if self.styleslist.index(i) == self.styleIndex: i.setChecked(True) else: i.setChecked(False) config.setstyleIndex(self.styleIndex) #self.initColorStyle() for i in range(len(self.files)): pass #self.tabWidget. #self.tabWidget.widget(i).setColorStyle(self.colorStyle)
def setMinimum(self, value): QSlider.setMinimum(self, self.convert(value))
class FeeSelectionDialog(ArmoryDialog): ############################################################################# def __init__(self, parent, main, cs_callback, get_csstate): super(FeeSelectionDialog, self).__init__(parent, main) #Button Label self.lblButtonFee = QLabelButton("") #get default values flatFee = self.main.getSettingOrSetDefault("Default_Fee", MIN_TX_FEE) flatFee = coin2str(flatFee, maxZeros=1).strip() fee_byte = str(self.main.getSettingOrSetDefault("Default_FeeByte", MIN_FEE_BYTE)) blocksToConfirm = self.main.getSettingOrSetDefault(\ "Default_FeeByte_BlocksToConfirm", NBLOCKS_TO_CONFIRM) feeStrategy = str(self.main.getSettingOrSetDefault(\ "Default_FeeByte_Strategy", FEEBYTE_CONSERVATIVE)) self.coinSelectionCallback = cs_callback self.getCoinSelectionState = get_csstate self.validAutoFee = True isSmartFee = True try: feeEstimate, isSmartFee, errorMsg = self.getFeeByteFromNode(blocksToConfirm, feeStrategy) except: feeEstimate = "N/A" self.validAutoFee = False defaultCheckState = \ self.main.getSettingOrSetDefault("FeeOption", DEFAULT_FEE_TYPE) #flat free def setFlatFee(): def callbck(): return self.selectType('FlatFee') return callbck def updateLbl(): self.updateCoinSelection() self.radioFlatFee = QRadioButton(self.tr("Flat Fee (BTC)")) self.edtFeeAmt = QLineEdit(flatFee) self.edtFeeAmt.setFont(GETFONT('Fixed')) self.edtFeeAmt.setMinimumWidth(tightSizeNChar(self.edtFeeAmt, 6)[0]) self.edtFeeAmt.setMaximumWidth(tightSizeNChar(self.edtFeeAmt, 12)[0]) self.connect(self.radioFlatFee, SIGNAL('clicked()'), setFlatFee()) self.connect(self.edtFeeAmt, SIGNAL('textChanged(QString)'), updateLbl) frmFlatFee = QFrame() frmFlatFee.setFrameStyle(STYLE_RAISED) layoutFlatFee = QGridLayout() layoutFlatFee.addWidget(self.radioFlatFee, 0, 0, 1, 1) layoutFlatFee.addWidget(self.edtFeeAmt, 0, 1, 1, 1) frmFlatFee.setLayout(layoutFlatFee) #fee/byte def setFeeByte(): def callbck(): return self.selectType('FeeByte') return callbck self.radioFeeByte = QRadioButton(self.tr("Fee/Byte (Satoshi/Byte)")) self.edtFeeByte = QLineEdit(fee_byte) self.edtFeeByte.setFont(GETFONT('Fixed')) self.edtFeeByte.setMinimumWidth(tightSizeNChar(self.edtFeeByte, 6)[0]) self.edtFeeByte.setMaximumWidth(tightSizeNChar(self.edtFeeByte, 12)[0]) self.connect(self.radioFeeByte, SIGNAL('clicked()'), setFeeByte()) self.connect(self.edtFeeByte, SIGNAL('textChanged(QString)'), updateLbl) frmFeeByte = QFrame() frmFeeByte.setFrameStyle(STYLE_RAISED) layoutFeeByte = QGridLayout() layoutFeeByte.addWidget(self.radioFeeByte, 0, 0, 1, 1) layoutFeeByte.addWidget(self.edtFeeByte, 0, 1, 1, 1) frmFeeByte.setLayout(layoutFeeByte) #auto fee/byte if isSmartFee: frmAutoFeeByte = self.setupSmartAutoFeeByteUI(\ feeEstimate, blocksToConfirm, feeStrategy) else: frmAutoFeeByte = self.setupLegacyAutoFeeByteUI(\ feeEstimate, blocksToConfirm) #adjust and close self.btnClose = QPushButton(self.tr('Close')) self.connect(self.btnClose, SIGNAL('clicked()'), self.accept) self.checkBoxAdjust = QCheckBox(self.tr('Adjust fee/byte for privacy')) self.checkBoxAdjust.setChecked(\ self.main.getSettingOrSetDefault('AdjustFee', True)) self.connect(self.checkBoxAdjust, SIGNAL('clicked()'), updateLbl) frmClose = makeHorizFrame(\ [self.checkBoxAdjust, 'Stretch', self.btnClose], STYLE_NONE) #main layout layout = QGridLayout() layout.addWidget(frmAutoFeeByte, 0, 0, 1, 4) layout.addWidget(frmFeeByte, 2, 0, 1, 4) layout.addWidget(frmFlatFee, 4, 0, 1, 4) layout.addWidget(frmClose, 5, 0, 1, 4) self.setLayout(layout) self.setWindowTitle(self.tr('Select Fee Type')) self.selectType(defaultCheckState) self.setFocus() ############################################################################# def setupLegacyAutoFeeByteUI(self, feeEstimate, blocksToConfirm): def setAutoFeeByte(): def callbck(): return self.selectType('Auto') return callbck def updateLbl(): self.updateCoinSelection() def feeByteToStr(feeByte): try: self.feeByte = feeByte return "<u>%.1f</u>" % feeByte except: self.feeByte = -1 if isinstance(feeByte, str): return feeByte else: return "N/A" radioButtonTxt = self.tr("Fee rate from node (sat/Byte): ") if not self.validAutoFee: radioButtonTxt = self.tr("Failed to fetch fee/byte from node") self.radioAutoFeeByte = QRadioButton(radioButtonTxt) self.lblAutoFeeByte = QLabel(feeByteToStr(feeEstimate)) self.lblAutoFeeByte.setFont(GETFONT('Fixed')) self.lblAutoFeeByte.setMinimumWidth(tightSizeNChar(self.lblAutoFeeByte, 6)[0]) self.lblAutoFeeByte.setMaximumWidth(tightSizeNChar(self.lblAutoFeeByte, 12)[0]) self.sliderAutoFeeByte = QSlider(Qt.Horizontal, self) self.sliderAutoFeeByte.setMinimum(2) self.sliderAutoFeeByte.setMaximum(6) self.sliderAutoFeeByte.setValue(blocksToConfirm) self.lblSlider = QLabel() def getSliderLabelTxt(): return self.tr("Blocks to confirm: %1").arg(\ unicode(self.sliderAutoFeeByte.value())) def updateAutoFeeByte(): blocksToConfirm = self.sliderAutoFeeByte.value() try: feeEstimate, version, err = \ self.getFeeByteFromNode(blocksToConfirm, FEEBYTE_CONSERVATIVE) except: feeEstimate = "N/A" self.lblSlider.setText(getSliderLabelTxt()) self.lblAutoFeeByte.setText(feeByteToStr(feeEstimate)) updateLbl() self.lblSlider.setText(getSliderLabelTxt()) self.connect(self.radioAutoFeeByte, SIGNAL('clicked()'), setAutoFeeByte()) self.sliderAutoFeeByte.valueChanged.connect(updateAutoFeeByte) self.sliderAutoFeeByte.setEnabled(False) frmAutoFeeByte = QFrame() frmAutoFeeByte.setFrameStyle(STYLE_RAISED) layoutAutoFeeByte = QGridLayout() layoutAutoFeeByte.addWidget(self.radioAutoFeeByte, 0, 0, 1, 1) layoutAutoFeeByte.addWidget(self.lblAutoFeeByte, 0, 1, 1, 1) layoutAutoFeeByte.addWidget(self.lblSlider, 1, 0, 1, 2) layoutAutoFeeByte.addWidget(self.sliderAutoFeeByte, 2, 0, 1, 2) frmAutoFeeByte.setLayout(layoutAutoFeeByte) if not self.validAutoFee: frmAutoFeeByte.setEnabled(False) return frmAutoFeeByte ############################################################################# def setupSmartAutoFeeByteUI(self, feeEstimate, blocksToConfirm, strat): def setAutoFeeByte(): def callbck(): return self.selectType('Auto') return callbck stratList = [FEEBYTE_CONSERVATIVE, FEEBYTE_ECONOMICAL] def updateLbl(): self.updateCoinSelection() def getStrategyString(): try: cbIndex = self.comboStrat.currentIndex() return stratList[cbIndex] except: return FEEBYTE_CONSERVATIVE def feeByteToStr(feeByte): try: self.feeByte = feeByte return "<u>%.1f</u>" % feeByte except: self.feeByte = -1 if isinstance(feeByte, str): return feeByte else: return "N/A" radioButtonTxt = self.tr("Fee rate from node (sat/Byte): ") if not self.validAutoFee: radioButtonTxt = self.tr("Failed to fetch fee/byte from node") self.radioAutoFeeByte = QRadioButton(radioButtonTxt) self.lblAutoFeeByte = QLabel(feeByteToStr(feeEstimate)) self.lblAutoFeeByte.setFont(GETFONT('Fixed')) self.lblAutoFeeByte.setMinimumWidth(tightSizeNChar(self.lblAutoFeeByte, 6)[0]) self.lblAutoFeeByte.setMaximumWidth(tightSizeNChar(self.lblAutoFeeByte, 12)[0]) self.sliderAutoFeeByte = QSlider(Qt.Horizontal, self) self.sliderAutoFeeByte.setMinimum(2) self.sliderAutoFeeByte.setMaximum(100) self.sliderAutoFeeByte.setValue(blocksToConfirm) self.lblSlider = QLabel() self.lblStrat = QLabel(self.tr("Profile:")) self.ttStart = self.main.createToolTipWidget(self.tr( ''' <u>Fee Estimation Profiles:</u><br><br> <b>CONSERVATIVE:</b> Short term estimate. More reactive to current changes in the mempool. Use this estimate if you want a high probability of getting your transaction mined quickly. <br><br> <b>ECONOMICAL:</b> Long term estimate. Ignores short term changes to the mempool. Use this profile if you want low fees and can tolerate swings in the projected confirmation window. <br><br> The estimate profiles may not diverge until your node has gathered enough data from the network to refine its predictions. Refer to the \"estimatesmartfee\" section in the Bitcoin Core 0.15 changelog for more informations. ''')) self.comboStrat = QComboBox() currentIndex = 0 for i in range(len(stratList)): self.comboStrat.addItem(stratList[i]) if stratList[i] == strat: currentIndex = i self.comboStrat.setCurrentIndex(currentIndex) def getSliderLabelTxt(): return self.tr("Blocks to confirm: %1").arg(\ unicode(self.sliderAutoFeeByte.value())) def updateAutoFeeByte(): blocksToConfirm = self.sliderAutoFeeByte.value() strategy = getStrategyString() try: feeEstimate, version, err = \ self.getFeeByteFromNode(blocksToConfirm, strategy) except: feeEstimate = "N/A" self.lblSlider.setText(getSliderLabelTxt()) self.lblAutoFeeByte.setText(feeByteToStr(feeEstimate)) updateLbl() def stratComboChange(): updateAutoFeeByte() self.lblSlider.setText(getSliderLabelTxt()) self.connect(self.radioAutoFeeByte, SIGNAL('clicked()'), setAutoFeeByte()) self.sliderAutoFeeByte.valueChanged.connect(updateAutoFeeByte) self.sliderAutoFeeByte.setEnabled(False) self.connect(self.comboStrat, SIGNAL('currentIndexChanged(int)'), stratComboChange) frmAutoFeeByte = QFrame() frmAutoFeeByte.setFrameStyle(STYLE_RAISED) layoutAutoFeeByte = QGridLayout() layoutAutoFeeByte.addWidget(self.radioAutoFeeByte, 0, 0, 1, 2) layoutAutoFeeByte.addWidget(self.lblAutoFeeByte, 0, 2, 1, 2) layoutAutoFeeByte.addWidget(self.lblSlider, 1, 0, 1, 1) layoutAutoFeeByte.addWidget(self.sliderAutoFeeByte, 2, 0, 1, 4) layoutAutoFeeByte.addWidget(self.lblStrat, 3, 0, 1, 1) layoutAutoFeeByte.addWidget(self.comboStrat, 3, 1, 1, 2) layoutAutoFeeByte.addWidget(self.ttStart, 3, 3, 1, 1) frmAutoFeeByte.setLayout(layoutAutoFeeByte) if not self.validAutoFee: frmAutoFeeByte.setEnabled(False) return frmAutoFeeByte ############################################################################# def getFeeByteFromNode(self, blocksToConfirm, strategy): try: feeEstimateResult = estimateFee(blocksToConfirm, strategy) return feeEstimateResult.val_ * 100000, \ feeEstimateResult.isSmart_, \ feeEstimateResult.error_ except: self.validAutoFee = False return "N/A", False, "" ############################################################################# def selectType(self, strType): self.radioFlatFee.setChecked(False) self.radioFeeByte.setChecked(False) self.radioAutoFeeByte.setChecked(False) self.sliderAutoFeeByte.setEnabled(False) if strType == 'FlatFee': self.radioFlatFee.setChecked(True) elif strType == 'FeeByte': self.radioFeeByte.setChecked(True) elif strType == 'Auto': if not self.validAutoFee: self.radioFeeByte.setChecked(True) else: self.radioAutoFeeByte.setChecked(True) self.sliderAutoFeeByte.setEnabled(True) self.updateCoinSelection() self.updateLabelButton() ############################################################################# def updateCoinSelection(self): try: self.coinSelectionCallback() except: self.updateLabelButton() ############################################################################# def getLabelButton(self): return self.lblButtonFee ############################################################################# def updateLabelButtonText(self, txSize, flatFee, fee_byte): txSize = str(txSize) if txSize != 'N/A': txSize += " B" if flatFee != 'N/A': flatFee = coin2str(flatFee, maxZeros=0).strip() flatFee += " BTC" if not isinstance(fee_byte, str): fee_byte = '%.2f' % fee_byte lblStr = "Size: %s, Fee: %s" % (txSize, flatFee) if fee_byte != 'N/A': lblStr += " (%s sat/B)" % fee_byte self.lblButtonFee.setText(lblStr) ############################################################################# def updateLabelButton(self, reset=False): try: if reset: raise Exception() txSize, flatFee, feeByte = self.getCoinSelectionState() self.updateLabelButtonText(txSize, flatFee, feeByte) except: self.updateLabelButtonText('N/A', 'N/A', 'N/A') ############################################################################# def resetLabel(self): self.updateLabelButton(True) ############################################################################# def getFeeData(self): fee = 0 fee_byte = 0 if self.radioFlatFee.isChecked(): flatFeeText = str(self.edtFeeAmt.text()) fee = str2coin(flatFeeText) elif self.radioFeeByte.isChecked(): fee_byteText = str(self.edtFeeByte.text()) fee_byte = float(fee_byteText) elif self.radioAutoFeeByte.isChecked(): fee_byte = self.feeByte adjust_fee = self.checkBoxAdjust.isChecked() return fee, fee_byte, adjust_fee ############################################################################# def setZeroFee(self): self.edtFeeAmt.setText('0') self.selectType('FlatFee')
class ControlBar(QWidget): """ Widget that contains the play/pause button, the progress bar and the speed slider. """ play = pyqtSignal(name="Play") pause = pyqtSignal(name="Pause") seek = pyqtSignal(float, name="Time changed") speedChanged = pyqtSignal(int, name="Speed changed") def __init__(self, duration: float, parent: QWidget = None): QWidget.__init__(self, parent) self.log = getLoggerPassFilters(LOGGER_NAMES.LIVEPLAYER) self.button = PlayPauseButton() self.button.setMaximumWidth(100) self.button.clicked.connect(self.onButtonClicked) self.timeSlider = ClickableProgressBar() self.timeSlider.setMinimum(0) self.timeSlider.setMaximum(int(duration * 1000)) self.timeSlider.valueChanged.connect(self.onSeek) self.speedLabel = QLabel("Speed: 1x") self.speedSlider = QSlider(Qt.Horizontal) self.speedSlider.setMaximumWidth(300) self.speedSlider.setMinimum(1) self.speedSlider.setMaximum(10) self.speedSlider.valueChanged.connect(self.onSpeedChanged) vertical = QVBoxLayout() horizontal = QHBoxLayout() horizontal.addWidget(self.speedLabel) horizontal.addWidget(self.speedSlider) horizontal.addItem(QSpacerItem(20, 40, QSizePolicy.Expanding, QSizePolicy.Expanding)) vertical.addLayout(horizontal) horizontal = QHBoxLayout() horizontal.addWidget(self.button) horizontal.addWidget(self.timeSlider) vertical.addLayout(horizontal) self.setLayout(vertical) self.setGeometry(0, 0, 80, 60) def onButtonClicked(self): if self.button.playing: self.log.debug("Play clicked") self.play.emit() else: self.log.debug("Pause clicked") self.pause.emit() def onSeek(self): time = self.timeSlider.value() / 1000.0 self.log.debug("Seek to %(arg1)d seconds", {"arg1": time}) self.seek.emit(time) def onSpeedChanged(self): speed = self.speedSlider.value() self.log.debug("Slider changed value: %(arg1)d", {"arg1": speed}) self.speedLabel.setText("Speed: {}x".format(speed)) self.speedChanged.emit(speed)
class MainWindow(QWidget): def __init__(self): QWidget.__init__(self, None) # initiate timer self.timer = QTimer() self.timer.timeout.connect(self.reload) # layout id gridbox-like self.box = QGridLayout() self.resize(800, 800) self.setLayout(self.box) # Create two labels and a button self.vertLabel = QLabel("Radolan Data Window", self) self.timeLabel = QLabel("Time", self) self.sliderLabel = QLabel("00:00", self) # File Dialog self.dlg = QFileDialog() self.dlg.setFileMode(QFileDialog.Directory) self.dlg.setOption(QFileDialog.ShowDirsOnly, True) # Canvas self.canvas = None self.cbar = CBarCanvas() # Sliders self.slider = QSlider(Qt.Horizontal) self.slider.setMinimum(1) self.slider.setMaximum(100) self.slider.setTickInterval(1) self.slider.setSingleStep(1) self.slider.valueChanged.connect(self.slider_moved) self.cHighSlider = QSlider(Qt.Horizontal) self.cHighSlider.setMinimum(0) self.cHighSlider.setMaximum(4096) self.cHighSlider.setTickInterval(1) self.cHighSlider.setSingleStep(1) self.cHighSlider.setValue(4096) self.cHighSlider.valueChanged.connect(self.cHighSlider_moved) self.cHighLabel = QLabel("Upper Limit:") self.cHighValue = QLabel("4096") # Load Button self.loadButton = QPushButton("Open Directory") self.loadButton.clicked.connect(self.button_clicked) # Text Output Widget self.attrWidget = TextWidget() self.attrWidget.setVisible(False) self.createButtons() # grid parameters self.c1 = 0 self.c2 = 10 # add Widgets to Layout self.box.addWidget(self.loadButton, 0, self.c1, 1, 11) self.box.addWidget(self.dlg, 1, self.c1, 3, 11) self.box.addWidget(self.attrWidget, 1, self.c1, 3, -1) self.box.addWidget(self.vertLabel, 6, self.c1, 1, 10) self.box.addWidget(self.cbar.native, 5, self.c2, 10, 1) self.box.addWidget(self.timeLabel, 4, self.c1, 1, 10) self.box.addWidget(self.playPauseButton, 4, self.c1 + 1, 1, 1) self.box.addWidget(self.cHighLabel, 4, self.c1 + 4, 1, 1) self.box.addWidget(self.cHighValue, 4, self.c1 + 5, 1, 1) self.box.addWidget(self.cHighSlider, 4, self.c1 + 6, 1, 4) self.box.addWidget(self.sliderLabel, 5, self.c1, 1, 1) self.box.addWidget(self.slider, 5, self.c1 + 1, 1, 9) self.show() # connect Filedialog self.dlg.fileSelected.connect(self.folder_selected) def folder_selected(self, folder): if not self.canvas: self.canvas = Canvas() self.box.addWidget(self.canvas.native, 7, self.c1, -1, 10) inname = "/raa*" self.canvas.flist = sorted(glob.glob(str(folder) + inname)) self.canvas.frames = len(self.canvas.flist) self.slider.setMaximum(self.canvas.frames) self.attrWidget.setVisible(True) self.slider.setValue(1) self.slider_moved(1) def button_clicked(self): self.attrWidget.setVisible(False) self.dlg.setVisible(True) # loop continuously through data def reload(self): if self.slider.value() == self.slider.maximum(): self.slider.setValue(1) else: self.slider.setValue(self.slider.value() + 1) # changing upper limit def cHighSlider_moved(self, position): clow, chigh = self.canvas.image.clim self.canvas.image.clim = (clow, position) self.cHighValue.setText(str(position)) # slide through data def slider_moved(self, position): self.canvas.actualFrame = position - 1 self.canvas.data, self.canvas.attrs = read_RADOLAN_composite(self.canvas.flist[self.canvas.actualFrame], missing=0) # adapt color limits if self.canvas.data.dtype == 'uint8': self.cHighSlider.setMaximum(255) else: self.cHighSlider.setMaximum(4096) # change and update self.canvas.update() self.sliderLabel.setText(self.canvas.attrs['datetime'].strftime("%H:%M")) self.attrWidget.radolanVersion.setText(self.canvas.attrs['radolanversion']) self.attrWidget.dateTime.setText(self.canvas.attrs['datetime'].strftime("%Y-%m-%d")) self.attrWidget.productType.setText(self.canvas.attrs['producttype'].upper()) # start/stop capability def playpause(self): if self.playPauseButton.toolTip() == 'Play': self.playPauseButton.setToolTip("Pause") self.timer.start() self.playPauseButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPause)) else: self.playPauseButton.setToolTip("Play") self.timer.stop() self.playPauseButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) # create play/pause Button def createButtons(self): iconSize = QSize(18, 18) self.playPauseButton = QToolButton() self.playPauseButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) self.playPauseButton.setIconSize(iconSize) self.playPauseButton.setToolTip("Play") self.playPauseButton.clicked.connect(self.playpause)
class MyMainWindow(QMainWindow): ' Main Window ' def __init__(self, AUTO): ' Initialize QWidget inside MyMainWindow ' super(MyMainWindow, self).__init__() QWidget.__init__(self) self.auto = AUTO self.statusBar().showMessage(' {}'.format(__doc__)) self.setStyleSheet('QStatusBar{color:grey;}') self.setWindowTitle(__doc__) self.setWindowIcon(QIcon.fromTheme("face-monkey")) self.setFont(QFont('Ubuntu Light', 10)) self.setMaximumSize(QDesktopWidget().screenGeometry().width(), QDesktopWidget().screenGeometry().height()) self.base = path.abspath(path.join(getcwd(), str(datetime.now().year))) # directory auto completer self.completer = QCompleter(self) self.dirs = QDirModel(self) self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot) self.completer.setModel(self.dirs) self.completer.setCaseSensitivity(Qt.CaseInsensitive) self.completer.setCompletionMode(QCompleter.PopupCompletion) # process self.process1 = None self.process2 = None self.cmd1 = 'nice -n {n} arecord{v} -f {f} -c {c} -r {b} -t raw' self.cmd2 = 'oggenc - -r -C {c} -R {b} -q {q} {d}{t}{a} -o {o}' self.process3 = QProcess(self) #self.process3.finished.connect(self.on_process3_finished) #self.process3.error.connect(self.on_process3_error) self.cmd3 = ('nice -n 20 ' + 'sox "{o}" -n spectrogram -x {x} -y {y} -z 99 -t "{o}" -o "{o}.png"') self.actual_file = '' # re starting timers, one stops, one starts self.timerFirst = QTimer(self) self.timerFirst.timeout.connect(self.end) self.timerSecond = QTimer(self) self.timerSecond.timeout.connect(self.run) # Proxy support, by reading http_proxy os env variable proxy_url = QUrl(environ.get('http_proxy', '')) QNetworkProxy.setApplicationProxy(QNetworkProxy(QNetworkProxy.HttpProxy if str(proxy_url.scheme()).startswith('http') else QNetworkProxy.Socks5Proxy, proxy_url.host(), proxy_url.port(), proxy_url.userName(), proxy_url.password())) \ if 'http_proxy' in environ else None print((' INFO: Proxy Auto-Config as ' + str(proxy_url))) # basic widgets layouts and set up self.mainwidget = QTabWidget() self.mainwidget.setToolTip(__doc__) self.mainwidget.setMovable(True) self.mainwidget.setTabShape(QTabWidget.Triangular) self.mainwidget.setContextMenuPolicy(Qt.CustomContextMenu) self.mainwidget.setStyleSheet('QTabBar{color:white;font-weight:bold;}') self.mainwidget.setTabBar(TabBar(self)) self.mainwidget.setTabsClosable(False) self.setCentralWidget(self.mainwidget) self.dock1 = QDockWidget() self.dock2 = QDockWidget() self.dock3 = QDockWidget() self.dock4 = QDockWidget() self.dock5 = QDockWidget() for a in (self.dock1, self.dock2, self.dock3, self.dock4, self.dock5): a.setWindowModality(Qt.NonModal) # a.setWindowOpacity(0.9) a.setWindowTitle(__doc__ if a.windowTitle() == '' else a.windowTitle()) a.setStyleSheet('QDockWidget::title{text-align:center;}') self.mainwidget.addTab(a, QIcon.fromTheme("face-smile"), 'Double Click Me') # Paleta de colores para pintar transparente self.palette().setBrush(QPalette.Base, Qt.transparent) self.setPalette(self.palette()) self.setAttribute(Qt.WA_OpaquePaintEvent, False) # toolbar and basic actions self.toolbar = QToolBar(self) self.toolbar.setIconSize(QSize(24, 24)) # spacer widget for left self.left_spacer = QWidget(self) self.left_spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) # spacer widget for right self.right_spacer = QWidget(self) self.right_spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) qaqq = QAction(QIcon.fromTheme("application-exit"), 'Quit', self) qaqq.setShortcut('Ctrl+Q') qaqq.triggered.connect(exit) qamin = QAction(QIcon.fromTheme("go-down"), 'Minimize', self) qamin.triggered.connect(lambda: self.showMinimized()) qamax = QAction(QIcon.fromTheme("go-up"), 'Maximize', self) qanor = QAction(QIcon.fromTheme("view-fullscreen"), 'AutoCenter AutoResize', self) qanor.triggered.connect(self.center) qatim = QAction(QIcon.fromTheme("mail-signed-verified"), 'View Date and Time', self) qatim.triggered.connect(self.timedate) qabug = QAction(QIcon.fromTheme("help-about"), 'Report a Problem', self) qabug.triggered.connect(lambda: qabug.setDisabled(True) if not call( 'xdg-open mailto:' + '*****@*****.**'.decode('rot13'), shell=True) else ' ERROR ') qamax.triggered.connect(lambda: self.showMaximized()) qaqt = QAction(QIcon.fromTheme("help-about"), 'About Qt', self) qaqt.triggered.connect(lambda: QMessageBox.aboutQt(self)) qakde = QAction(QIcon.fromTheme("help-about"), 'About KDE', self) if KDE: qakde.triggered.connect(KHelpMenu(self, "", False).aboutKDE) qaslf = QAction(QIcon.fromTheme("help-about"), 'About Self', self) if KDE: qaslf.triggered.connect( KAboutApplicationDialog(aboutData, self).exec_) else: qaslf.triggered.connect(lambda: QMessageBox.about(self.mainwidget, __doc__, ''.join((__doc__, linesep, 'version ', __version__, ', (', __license__, '), by ', __author__, ', ( ', __email__, ' )', linesep )))) qafnt = QAction(QIcon.fromTheme("tools-check-spelling"), 'Set GUI Font', self) if KDE: font = QFont() qafnt.triggered.connect(lambda: self.setStyleSheet(''.join(( '*{font-family:', str(font.toString()), '}')) if KFontDialog.getFont(font)[0] == QDialog.Accepted else '')) else: qafnt.triggered.connect(lambda: self.setStyleSheet(''.join(('*{font-family:', str(QFontDialog.getFont()[0].toString()), '}')))) qasrc = QAction(QIcon.fromTheme("applications-development"), 'View Source Code', self) qasrc.triggered.connect(lambda: call('xdg-open {}'.format(__file__), shell=True)) qakb = QAction(QIcon.fromTheme("input-keyboard"), 'Keyboard Shortcuts', self) qakb.triggered.connect(lambda: QMessageBox.information(self.mainwidget, 'Keyboard Shortcuts', ' Ctrl+Q = Quit ')) qapic = QAction(QIcon.fromTheme("camera-photo"), 'Take a Screenshot', self) qapic.triggered.connect(lambda: QPixmap.grabWindow( QApplication.desktop().winId()).save(QFileDialog.getSaveFileName( self.mainwidget, " Save Screenshot As ...", path.expanduser("~"), ';;(*.png) PNG', 'png'))) qatb = QAction(QIcon.fromTheme("go-top"), 'Toggle ToolBar', self) qatb.triggered.connect(lambda: self.toolbar.hide() if self.toolbar.isVisible() is True else self.toolbar.show()) qati = QAction(QIcon.fromTheme("zoom-in"), 'Switch ToolBar Icon Size', self) qati.triggered.connect(lambda: self.toolbar.setIconSize(self.toolbar.iconSize() * 4) if self.toolbar.iconSize().width() * 4 == 24 else self.toolbar.setIconSize(self.toolbar.iconSize() / 4)) qasb = QAction(QIcon.fromTheme("preferences-other"), 'Toggle Tabs Bar', self) qasb.triggered.connect(lambda: self.mainwidget.tabBar().hide() if self.mainwidget.tabBar().isVisible() is True else self.mainwidget.tabBar().show()) qadoc = QAction(QIcon.fromTheme("help-browser"), 'On-line Docs', self) qadoc.triggered.connect(lambda: open_new_tab(str(__url__).strip())) qapy = QAction(QIcon.fromTheme("help-about"), 'About Python', self) qapy.triggered.connect(lambda: open_new_tab('http://python.org/about')) qali = QAction(QIcon.fromTheme("help-browser"), 'Read Licence', self) qali.triggered.connect(lambda: open_new_tab(__full_licence__)) qacol = QAction(QIcon.fromTheme("preferences-system"), 'Set GUI Colors', self) if KDE: color = QColor() qacol.triggered.connect(lambda: self.setStyleSheet(''.join(('* { background-color: ', str(color.name()), '}'))) if KColorDialog.getColor(color, self) else '') else: qacol.triggered.connect(lambda: self.setStyleSheet(''.join(( ' * { background-color: ', str(QColorDialog.getColor().name()), ' } ')))) qatit = QAction(QIcon.fromTheme("preferences-system"), 'Set the App Window Title', self) qatit.triggered.connect(self.seTitle) self.toolbar.addWidget(self.left_spacer) self.toolbar.addSeparator() self.toolbar.addActions((qaqq, qamin, qanor, qamax, qasrc, qakb, qacol, qatim, qatb, qafnt, qati, qasb, qatit, qapic, qadoc, qali, qaslf, qaqt, qakde, qapy, qabug)) self.addToolBar(Qt.TopToolBarArea, self.toolbar) self.toolbar.addSeparator() self.toolbar.addWidget(self.right_spacer) # define the menu menu = self.menuBar() # File menu items menu.addMenu('&File').addActions((qaqq, )) menu.addMenu('&Window').addActions((qamax, qanor, qamin)) # Settings menu menu.addMenu('&Settings').addActions((qasrc, qacol, qafnt, qatim, qatb, qati, qasb, qapic)) # Help menu items menu.addMenu('&Help').addActions((qadoc, qakb, qabug, qali, qaqt, qakde, qapy, qaslf)) # Tray Icon tray = QSystemTrayIcon(QIcon.fromTheme("face-devilish"), self) tray.setToolTip(__doc__) traymenu = QMenu() traymenu.addActions((qamax, qanor, qamin, qaqq)) tray.setContextMenu(traymenu) tray.show() def contextMenuRequested(point): ' quick and dirty custom context menu ' menu = QMenu() menu.addActions((qaqq, qamin, qanor, qamax, qasrc, qakb, qacol, qafnt, qati, qasb, qatb, qatim, qatit, qapic, qadoc, qali, qaslf, qaqt, qakde, qapy, qabug)) menu.exec_(self.mapToGlobal(point)) self.mainwidget.customContextMenuRequested.connect(contextMenuRequested) def must_be_checked(widget_list): ' widget tuple passed as argument should be checked as ON ' for each_widget in widget_list: try: each_widget.setChecked(True) except: pass def must_have_tooltip(widget_list): ' widget tuple passed as argument should have tooltips ' for each_widget in widget_list: try: each_widget.setToolTip(each_widget.text()) except: each_widget.setToolTip(each_widget.currentText()) finally: each_widget.setCursor(QCursor(Qt.PointingHandCursor)) def must_autofillbackground(widget_list): ' widget tuple passed as argument should have filled background ' for each_widget in widget_list: try: each_widget.setAutoFillBackground(True) except: pass def must_glow(widget_list): ' apply an glow effect to the widget ' for glow, each_widget in enumerate(widget_list): try: if each_widget.graphicsEffect() is None: glow = QGraphicsDropShadowEffect(self) glow.setOffset(0) glow.setBlurRadius(99) glow.setColor(QColor(99, 255, 255)) each_widget.setGraphicsEffect(glow) # glow.setEnabled(False) try: each_widget.clicked.connect(lambda: each_widget.graphicsEffect().setEnabled(True) if each_widget.graphicsEffect().isEnabled() is False else each_widget.graphicsEffect().setEnabled(False)) except: each_widget.sliderPressed.connect(lambda: each_widget.graphicsEffect().setEnabled(True) if each_widget.graphicsEffect().isEnabled() is False else each_widget.graphicsEffect().setEnabled(False)) except: pass ####################################################################### # dock 1 QLabel('<h1 style="color:white;"> Record !</h1>', self.dock1).resize( self.dock3.size().width() / 4, 25) self.group1 = QGroupBox() self.group1.setTitle(__doc__) self.spec = QPushButton(self) self.spec.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.spec.setMinimumSize(self.spec.size().width(), 250) self.spec.setFlat(True) self.spec.clicked.connect(self.spectro) self.clock = QLCDNumber() self.clock.setSegmentStyle(QLCDNumber.Flat) self.clock.setMinimumSize(self.clock.size().width(), 50) self.clock.setNumDigits(25) self.timer1 = QTimer(self) self.timer1.timeout.connect(lambda: self.clock.display( datetime.now().strftime("%d-%m-%Y %H:%M:%S %p"))) self.timer1.start(1000) self.clock.setToolTip(datetime.now().strftime("%c %x")) self.clock.setCursor(QCursor(Qt.CrossCursor)) self.diskBar = QProgressBar() self.diskBar.setMinimum(0) self.diskBar.setMaximum(statvfs(HOME).f_blocks * statvfs(HOME).f_frsize / 1024 / 1024 / 1024) self.diskBar.setValue(statvfs(HOME).f_bfree * statvfs(HOME).f_frsize / 1024 / 1024 / 1024) self.diskBar.setToolTip(str(statvfs(HOME).f_bfree * statvfs(HOME).f_frsize / 1024 / 1024 / 1024) + ' Gigabytes free') self.feedback = QPlainTextEdit(''.join(('<center><h3>', __doc__, ', version', __version__, __license__, ' <br> by ', __author__, ' <i>(Dev)</i>, Radio Comunitaria FM Reconquista <i>(Q.A.)</i><br>', 'FMReconquista.org.ar & GitHub.com/JuanCarlosPaco/Cinta-Testigo'))) self.rec = QPushButton(QIcon.fromTheme("media-record"), 'Record') self.rec.setMinimumSize(self.rec.size().width(), 50) self.rec.clicked.connect(self.go) # self.run self.stop = QPushButton(QIcon.fromTheme("media-playback-stop"), 'Stop') self.stop.clicked.connect(self.end) self.kill = QPushButton(QIcon.fromTheme("process-stop"), 'Kill') self.kill.clicked.connect(self.killer) vboxg1 = QVBoxLayout(self.group1) for each_widget in ( QLabel('<b style="color:white;"> Spectro'), self.spec, QLabel('<b style="color:white;"> Time '), self.clock, QLabel('<b style="color:white;"> Disk '), self.diskBar, QLabel('<b style="color:white;"> STDOUT + STDIN '), self.feedback, QLabel('<b style="color:white;"> Record '), self.rec, self.stop, self.kill): vboxg1.addWidget(each_widget) self.group2 = QGroupBox() self.group2.setTitle(__doc__) self.slider = QSlider(self) self.slid_l = QLabel(self.slider) self.slider.setCursor(QCursor(Qt.OpenHandCursor)) self.slider.sliderPressed.connect(lambda: self.slider.setCursor(QCursor(Qt.ClosedHandCursor))) self.slider.sliderReleased.connect(lambda: self.slider.setCursor(QCursor(Qt.OpenHandCursor))) self.slider.valueChanged.connect(lambda: self.slider.setToolTip(str(self.slider.value()))) self.slider.valueChanged.connect(lambda: self.slid_l.setText( '<h2 style="color:white;">{}'.format(self.slider.value()))) self.slider.setMinimum(10) self.slider.setMaximum(99) self.slider.setValue(30) self.slider.setOrientation(Qt.Vertical) self.slider.setTickPosition(QSlider.TicksBothSides) self.slider.setTickInterval(2) self.slider.setSingleStep(10) self.slider.setPageStep(10) vboxg2 = QVBoxLayout(self.group2) for each_widget in ( QLabel('<b style="color:white;">MINUTES of recording'), self.slider, QLabel('<b style="color:white;"> Default: 30 Min')): vboxg2.addWidget(each_widget) group3 = QGroupBox() group3.setTitle(__doc__) try: self.label2 = QLabel(getoutput('sox --version', shell=True)) self.label4 = QLabel(getoutput('arecord --version', shell=1)[:25]) self.label6 = QLabel(str(getoutput('oggenc --version', shell=True))) except: print(''' ERROR: No SOX, OGGenc avaliable ! ( sudo apt-get install vorbis-tools sox alsa-utils ) ''') exit() self.button5 = QPushButton(QIcon.fromTheme("audio-x-generic"), 'OGG --> ZIP') self.button5.clicked.connect(lambda: make_archive( str(QFileDialog.getSaveFileName(self, "Save OGG to ZIP file As...", getcwd(), ';;(*.zip)', 'zip')).replace('.zip', ''), "zip", path.abspath(path.join(getcwd(), str(datetime.now().year))))) self.button1 = QPushButton(QIcon.fromTheme("folder-open"), 'Files') self.button1.clicked.connect(lambda: call('xdg-open ' + getcwd(), shell=True)) self.button0 = QPushButton( QIcon.fromTheme("preferences-desktop-screensaver"), 'LCD OFF') self.button0.clicked.connect(lambda: call('sleep 3 ; xset dpms force off', shell=True)) vboxg3 = QVBoxLayout(group3) for each_widget in ( QLabel('<b style="color:white;"> OGG Output Codec '), self.label6, QLabel('<b style="color:white;"> Raw Record Backend '), self.label4, QLabel('<b style="color:white;"> Helper Libs '), self.label2, QLabel('<b style="color:white;"> OGG ZIP '), self.button5, QLabel('<b style="color:white;"> Files '), self.button1, QLabel('<b style="color:white;"> LCD '), self.button0): vboxg3.addWidget(each_widget) container = QWidget() hbox = QHBoxLayout(container) for each_widget in (self.group2, self.group1, group3): hbox.addWidget(each_widget) self.dock1.setWidget(container) # dock 2 QLabel('<h1 style="color:white;"> Hardware !</h1>', self.dock2).resize( self.dock2.size().width() / 4, 25) try: audioDriverStr = {Solid.AudioInterface.Alsa: "ALSA", Solid.AudioInterface.OpenSoundSystem: "Open Sound", Solid.AudioInterface.UnknownAudioDriver: "Unknown?"} audioInterfaceTypeStr = { Solid.AudioInterface.AudioControl: "Control", Solid.AudioInterface.UnknownAudioInterfaceType: "Unknown?", Solid.AudioInterface.AudioInput: "In", Solid.AudioInterface.AudioOutput: "Out"} soundcardTypeStr = { Solid.AudioInterface.InternalSoundcard: "Internal", Solid.AudioInterface.UsbSoundcard: "USB3", Solid.AudioInterface.FirewireSoundcard: "FireWire", Solid.AudioInterface.Headset: "Headsets", Solid.AudioInterface.Modem: "Modem"} display = QTreeWidget() display.setAlternatingRowColors(True) display.setHeaderLabels(["Items", "ID", "Drivers", "I / O", "Type"]) display.setColumnWidth(0, 350) display.setColumnWidth(1, 350) display.setColumnWidth(3, 75) # retrieve a list of Solid.Device for this machine deviceList = Solid.Device.allDevices() # filter the list of all devices and display matching results # note that we never create a Solid.AudioInterface object, but # receive one from the 'asDeviceInterface' call for device in deviceList: if device.isDeviceInterface( Solid.DeviceInterface.AudioInterface): audio = device.asDeviceInterface( Solid.DeviceInterface.AudioInterface) devtype = audio.deviceType() devstr = [] for key in audioInterfaceTypeStr: flag = key & devtype if flag: devstr.append(audioInterfaceTypeStr[key]) QTreeWidgetItem(display, [device.product(), audio.name(), audioDriverStr[audio.driver()], "/".join(devstr), soundcardTypeStr[audio.soundcardType()]]) self.dock2.setWidget(display) except: self.dock2.setWidget(QLabel(""" <center style='color:white;'> <h1>:(<br>ERROR: Please, install PyKDE !</h1><br> <br><i> (Sorry, can not use non-Qt Libs). Thanks </i><center>""")) ## dock 3 QLabel('<h1 style="color:white;"> Previews !</h1>', self.dock3).resize( self.dock3.size().width() / 4, 25) self.fileView = QColumnView() self.fileView.updatePreviewWidget.connect(self.play) self.fileView.setToolTip(' Browse and Preview Files ') self.media = None self.model = QDirModel() self.fileView.setModel(self.model) self.dock3.setWidget(self.fileView) # dock4 QLabel('<h1 style="color:white;"> Setup !</h1>', self.dock4).resize( self.dock4.size().width() / 4, 25) self.group4 = QGroupBox() self.group4.setTitle(__doc__) self.combo0 = QComboBox() self.combo0.addItems(['S16_LE', 'S32_LE', 'S16_BE', 'U16_LE', 'U16_BE', 'S24_LE', 'S24_BE', 'U24_LE', 'U24_BE', 'S32_BE', 'U32_LE', 'U32_BE']) self.combo1 = QComboBox() self.combo1.addItems(['1', '-1', '0', '2', '3', '4', '5', '6', '7', '8', '9', '10']) self.combo2 = QComboBox() self.combo2.addItems(['128', '256', '512', '1024', '64', '32', '16']) self.combo3 = QComboBox(self) self.combo3.addItems(['MONO', 'STEREO', 'Surround']) self.combo4 = QComboBox() self.combo4.addItems(['44100', '96000', '48000', '32000', '22050', '16000', '11025', '8000']) self.combo5 = QComboBox(self) self.combo5.addItems(['20', '19', '18', '17', '16', '15', '14', '13', '12', '10', '9', '8', '7', '6', '5', '4', '3', '2', '1', '0']) self.nepochoose = QCheckBox('Auto-Tag Files using Nepomuk Semantic') self.chckbx0 = QCheckBox('Disable Software based Volume Control') self.chckbx1 = QCheckBox('Output Sound Stereo-to-Mono Downmix') self.chckbx2 = QCheckBox('Add Date and Time MetaData to Sound files') self.chckbx3 = QCheckBox('Add Yourself as the Author Artist of Sound') vboxg4 = QVBoxLayout(self.group4) for each_widget in ( QLabel('<b style="color:white;"> Sound OGG Quality'), self.combo1, QLabel('<b style="color:white;"> Sound Record Format'), self.combo0, QLabel('<b style="color:white;"> Sound KBps '), self.combo2, QLabel('<b style="color:white;"> Sound Channels '), self.combo3, QLabel('<b style="color:white;"> Sound Sample Rate '), self.combo4, QLabel('<b style="color:white;"> Sound Volume'), self.chckbx0, QLabel('<b style="color:white;"> Sound Mix'), self.chckbx1, QLabel('<b style="color:white;"> Sound Meta'), self.chckbx2, QLabel('<b style="color:white;"> Sound Authorship'), self.chckbx3, QLabel('<b style="color:white;"> CPUs Priority'), self.combo5, QLabel('<b style="color:white;">Nepomuk Semantic User Experience'), self.nepochoose): vboxg4.addWidget(each_widget) self.dock4.setWidget(self.group4) # dock 5 QLabel('<h1 style="color:white;"> Voice Changer ! </h1>', self.dock5 ).resize(self.dock5.size().width() / 3, 25) self.group5 = QGroupBox() self.group5.setTitle(__doc__) self.dial = QDial() self.dial.setCursor(QCursor(Qt.OpenHandCursor)) self.di_l = QLabel(self.dial) self.di_l.resize(self.dial.size() / 8) self.dial.sliderPressed.connect(lambda: self.dial.setCursor(QCursor(Qt.ClosedHandCursor))) self.dial.sliderReleased.connect(lambda: self.dial.setCursor(QCursor(Qt.OpenHandCursor))) self.dial.valueChanged.connect(lambda: self.dial.setToolTip(str(self.dial.value()))) self.dial.valueChanged.connect(lambda: self.di_l.setText( '<h1 style="color:white;">{}'.format(self.dial.value()))) self.dial.setValue(0) self.dial.setMinimum(-999) self.dial.setMaximum(999) self.dial.setSingleStep(100) self.dial.setPageStep(100) self.dial.setWrapping(False) self.dial.setNotchesVisible(True) self.defo = QPushButton(QIcon.fromTheme("media-playback-start"), 'Run') self.defo.setMinimumSize(self.defo.size().width(), 50) self.defo.clicked.connect(lambda: self.process3.start( 'play -q -V0 "|rec -q -V0 -n -d -R riaa pitch {} "' .format(self.dial.value()) if int(self.dial.value()) != 0 else 'play -q -V0 "|rec -q -V0 --multi-threaded -n -d -R bend {} "' .format(' 3,2500,3 3,-2500,3 ' * 999))) self.qq = QPushButton(QIcon.fromTheme("media-playback-stop"), 'Stop') self.qq.clicked.connect(self.process3.kill) self.die = QPushButton(QIcon.fromTheme("process-stop"), 'Kill') self.die.clicked.connect(lambda: call('killall rec', shell=True)) vboxg5 = QVBoxLayout(self.group5) for each_widget in (self.dial, self.defo, self.qq, self.die): vboxg5.addWidget(each_widget) self.dock5.setWidget(self.group5) # configure some widget settings must_be_checked((self.nepochoose, self.chckbx1, self.chckbx2, self.chckbx3)) must_have_tooltip((self.label2, self.label4, self.label6, self.combo0, self.nepochoose, self.combo1, self.combo2, self.combo3, self.combo4, self.combo5, self.chckbx0, self.chckbx1, self.chckbx2, self.chckbx3, self.rec, self.stop, self.defo, self.qq, self.die, self.kill, self.button0, self.button1, self.button5)) must_autofillbackground((self.clock, self.label2, self.label4, self.label6, self.nepochoose, self.chckbx0, self.chckbx1, self.chckbx2, self.chckbx3)) must_glow((self.rec, self.dial, self.combo1)) self.nepomuk_get('testigo') if self.auto is True: self.go() def play(self, index): ' play with delay ' if not self.media: self.media = Phonon.MediaObject(self) audioOutput = Phonon.AudioOutput(Phonon.MusicCategory, self) Phonon.createPath(self.media, audioOutput) self.media.setCurrentSource(Phonon.MediaSource( self.model.filePath(index))) self.media.play() def end(self): ' kill it with fire ' print((' INFO: Stoping Processes at {}'.format(str(datetime.now())))) self.process1.terminate() self.process2.terminate() self.feedback.setText(''' <h5>Errors for RECORDER QProcess 1:</h5>{}<hr> <h5>Errors for ENCODER QProcess 2:</h5>{}<hr> <h5>Output for RECORDER QProcess 1:</h5>{}<hr> <h5>Output for ENCODER QProcess 2:</h5>{}<hr> '''.format(self.process1.readAllStandardError(), self.process2.readAllStandardError(), self.process1.readAllStandardOutput(), self.process2.readAllStandardOutput(), )) def killer(self): ' kill -9 ' QMessageBox.information(self.mainwidget, __doc__, ' KILL -9 was sent to the multi-process backend ! ') self.process1.kill() self.process2.kill() def go(self): ' run timeout re-starting timers ' self.timerFirst.start(int(self.slider.value()) * 60 * 1000 + 2000) self.timerSecond.start(int(self.slider.value()) * 60 * 1000 + 2010) self.run() def run(self): ' run forest run ' print((' INFO: Working at {}'.format(str(datetime.now())))) chnl = 1 if self.combo3.currentText() == 'MONO' else 2 print((' INFO: Using {} Channels . . . '.format(chnl))) btrt = int(self.combo4.currentText()) print((' INFO: Using {} Hz per Second . . . '.format(btrt))) threshold = int(self.dial.value()) print((' INFO: Using Thresold of {} . . . '.format(threshold))) print((' INFO: Using Recording time of {}'.format(self.slider.value()))) frmt = str(self.combo0.currentText()).strip() print((' INFO: Using Recording quality of {} ...'.format(frmt))) qlt = str(self.combo1.currentText()).strip() print((' INFO: Using Recording quality of {} ...'.format(qlt))) prio = str(self.combo5.currentText()).strip() print((' INFO: Using CPU Priority of {} ...'.format(prio))) downmix = '--downmix ' if self.chckbx1.isChecked() is True else '' print((' INFO: Using Downmix is {} ...'.format(downmix))) aut = '-a ' + getuser() if self.chckbx3.isChecked() is True else '' print((' INFO: The Author Artist of this sound is: {}'.format(aut))) T = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") tim = '--date {} '.format(T) if self.chckbx2.isChecked() is True else '' print((' INFO: The Date and Time of this sound is: {}'.format(tim))) vol = ' --disable-softvol' if self.chckbx0.isChecked() is True else '' print((' INFO: Software based Volume Control is: {}'.format(vol))) # make base directory try: mkdir(self.base) print((' INFO: Base Directory path created {}'.format(self.base))) except OSError: print((' INFO: Base Directory already exist {}'.format(self.base))) except: print((' ERROR: Can not create Directory ?, {}'.format(self.base))) # make directory tree try: for dr in range(1, 13): mkdir(path.abspath(path.join(self.base, str(dr)))) print((' INFO:Directory created {}/{}'.format(self.base, dr))) except OSError: print((' INFO: Directory already exist {}/1,12'.format(self.base))) except: print((' ERROR: Cant create Directory?, {}/1,12'.format(self.base))) # make new filename flnm = path.abspath(path.join(self.base, str(datetime.now().month), datetime.now().strftime("%Y-%m-%d_%H:%M:%S.ogg"))) self.actual_file = flnm print((' INFO: Recording on the file {}'.format(flnm))) # make custom commands cmd1 = self.cmd1.format(n=prio, f=frmt, c=chnl, b=btrt, v=vol) cmd2 = self.cmd2.format(c=chnl, b=btrt, q=qlt, d=downmix, o=flnm, a=aut, t=tim) print((cmd1, cmd2)) # multiprocess recording loop pipe self.process1 = QProcess(self) self.process2 = QProcess(self) self.process1.setStandardOutputProcess(self.process2) self.process1.start(cmd1) if not self.process1.waitForStarted(): print((" ERROR: RECORDER QProcess 1 Failed: \n {} ".format(cmd1))) self.process2.start(cmd2) if not self.process2.waitForStarted(): print((" ERROR: ENCODER QProcess 2 Failed: \n {} ".format(cmd2))) self.nepomuk_set(flnm, 'testigo', 'testigo', 'AutoTag by Cinta-Testigo') def spectro(self): ' spectrometer ' wid = self.spec.size().width() hei = self.spec.size().height() command = self.cmd3.format(o=self.actual_file, x=wid, y=hei) print(' INFO: Spectrometer is deleting OLD .ogg.png Files on target ') call('rm --verbose --force {}/*/*.ogg.png'.format(self.base), shell=1) print(' INFO: Spectrometer finished Deleting Files, Starting Render ') call(command, shell=True) print((''' INFO: Spectrometer finished Rendering Sound using: {}{} OutPut: {}'''.format(command, linesep, self.actual_file))) self.spec.setIcon(QIcon('{o}.png'.format(o=self.actual_file))) self.spec.setIconSize(QSize(wid, hei)) self.spec.resize(wid, hei) ########################################################################### def paintEvent(self, event): 'Paint semi-transparent background, animated pattern, background text' QWidget.paintEvent(self, event) # make a painter p = QPainter(self) p.setRenderHint(QPainter.TextAntialiasing) p.setRenderHint(QPainter.HighQualityAntialiasing) # fill a rectangle with transparent painting p.fillRect(event.rect(), Qt.transparent) # animated random dots background pattern for i in range(4096): x = randint(9, self.size().width() - 9) y = randint(9, self.size().height() - 9) p.setPen(QPen(QColor(randint(200, 255), randint(200, 255), 255), 1)) p.drawPoint(x, y) # set pen to use white color p.setPen(QPen(QColor(randint(9, 255), randint(9, 255), 255), 1)) # Rotate painter 45 Degree p.rotate(35) # Set painter Font for text p.setFont(QFont('Ubuntu', 300)) # draw the background text, with antialiasing p.drawText(99, 199, "Radio") # Rotate -45 the QPen back ! p.rotate(-35) # set the pen to no pen p.setPen(Qt.NoPen) # Background Color p.setBrush(QColor(0, 0, 0)) # Background Opacity p.setOpacity(0.75) # Background Rounded Borders p.drawRoundedRect(self.rect(), 50, 50) # finalize the painter p.end() def seTitle(self): ' set the title of the main window ' dialog = QDialog(self) textEditInput = QLineEdit(' Type Title Here ') ok = QPushButton(' O K ') ok.clicked.connect(lambda: self.setWindowTitle(textEditInput.text())) ly = QVBoxLayout() [ly.addWidget(wdgt) for wdgt in (QLabel('Title:'), textEditInput, ok)] dialog.setLayout(ly) dialog.exec_() def timedate(self): ' get the time and date ' dialog = QDialog(self) clock = QLCDNumber() clock.setNumDigits(24) timer = QTimer() timer.timeout.connect(lambda: clock.display( datetime.now().strftime("%d-%m-%Y %H:%M:%S %p"))) timer.start(1000) clock.setToolTip(datetime.now().strftime("%c %x")) ok = QPushButton(' O K ') ok.clicked.connect(dialog.close) ly = QVBoxLayout() [ly.addWidget(wdgt) for wdgt in (QCalendarWidget(), clock, ok)] dialog.setLayout(ly) dialog.exec_() def closeEvent(self, event): ' Ask to Quit ' if QMessageBox.question(self, ' Close ', ' Quit ? ', QMessageBox.Yes | QMessageBox.No, QMessageBox.No) == QMessageBox.Yes: event.accept() else: event.ignore() def center(self): ' Center and resize the window ' self.showNormal() self.resize(QDesktopWidget().screenGeometry().width() // 1.25, QDesktopWidget().screenGeometry().height() // 1.25) qr = self.frameGeometry() qr.moveCenter(QDesktopWidget().availableGeometry().center()) self.move(qr.topLeft()) def nepomuk_set(self, file_tag=None, __tag='', _label='', _description=''): ' Quick and Easy Nepomuk Taggify for Files ' print((''' INFO: Semantic Desktop Experience is Tagging Files : {}, {}, {}, {})'''.format(file_tag, __tag, _label, _description))) if Nepomuk.ResourceManager.instance().init() is 0: fle = Nepomuk.Resource(KUrl(QFileInfo(file_tag).absoluteFilePath())) _tag = Nepomuk.Tag(__tag) _tag.setLabel(_label) fle.addTag(_tag) fle.setDescription(_description) print(([str(a.label()) for a in fle.tags()], fle.description())) return ([str(a.label()) for a in fle.tags()], fle.description()) else: print(" ERROR: FAIL: Nepomuk is not running ! ") def nepomuk_get(self, query_to_search): ' Quick and Easy Nepomuk Query for Files ' print((''' INFO: Semantic Desktop Experience is Quering Files : {} '''.format(query_to_search))) results = [] nepo = Nepomuk.Query.QueryServiceClient() nepo.desktopQuery("hasTag:{}".format(query_to_search)) def _query(data): ''' ('filename.ext', 'file description', ['list', 'of', 'tags']) ''' results.append(([str(a.resource().genericLabel()) for a in data][0], [str(a.resource().description()) for a in data][0], [str(a.label()) for a in iter([a.resource().tags() for a in data][0] )])) nepo.newEntries.connect(_query) def _end(): ''' [ ('filename.ext', 'file description', ['list', 'of', 'tags']), ('filename.ext', 'file description', ['list', 'of', 'tags']), ('filename.ext', 'file description', ['list', 'of', 'tags']) ] ''' nepo.newEntries.disconnect print(results) return results nepo.finishedListing.connect(_end)
class XZoomSlider(QWidget): zoomAmountChanged = Signal(int) def __init__(self, parent=None): super(XZoomSlider, self).__init__(parent) # define the interface in_icon = projexui.resources.find('img/zoom_in.png') out_icon = projexui.resources.find('img/zoom_out.png') self._zoomInButton = QToolButton(self) self._zoomInButton.setAutoRaise(True) self._zoomInButton.setToolTip('Zoom In') self._zoomInButton.setIcon(QIcon(in_icon)) self._zoomOutButton = QToolButton(self) self._zoomOutButton.setAutoRaise(True) self._zoomOutButton.setToolTip('Zoom Out') self._zoomOutButton.setIcon(QIcon(out_icon)) self._zoomSlider = QSlider(Qt.Horizontal, self) self._zoomSlider.setRange(10, 100) self._zoomSlider.setValue(100) # define the layout layout = QHBoxLayout() layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(0) layout.addWidget(self._zoomOutButton) layout.addWidget(self._zoomSlider) layout.addWidget(self._zoomInButton) self.setLayout(layout) # create connections self._zoomSlider.valueChanged.connect(self.emitZoomAmountChanged) self._zoomInButton.clicked.connect(self.zoomIn) self._zoomOutButton.clicked.connect(self.zoomOut) def emitZoomAmountChanged(self): """ Emits the current zoom amount, provided the signals are not being blocked. """ if not self.signalsBlocked(): self.zoomAmountChanged.emit(self.zoomAmount()) def maximum(self): """ Returns the maximum zoom level for this widget. :return <int> """ return self._zoomSlider.maximum() def minimum(self): """ Returns the minimum zoom level for this widget. :return <int> """ return self._zoomSlider.minimum() def setMaximum(self, maximum): """ Sets the maximum zoom level for this widget. :param maximum | <int> """ self._zoomSlider.setMaximum(minimum) def setMinimum(self, minimum): """ Sets the minimum zoom level for this widget. :param minimum | <int> """ self._zoomSlider.setMinimum(minimum) def setZoomStep(self, amount): """ Sets how much a single step for the zoom in/out will be. :param amount | <int> """ self._zoomSlider.setPageStep(amount) @Slot(int) def setZoomAmount(self, amount): """ Sets the zoom amount for this widget to the inputed amount. :param amount | <int> """ self._zoomSlider.setValue(amount) def zoomAmount(self): """ Returns the current zoom amount for this widget. :return <int> """ return self._zoomSlider.value() @Slot() def zoomIn(self): """ Zooms in by a single page step. """ self._zoomSlider.triggerAction(QSlider.SliderPageStepAdd) def zoomInButton(self): """ Returns the zoom in button from the left side of this widget. :return <QToolButton> """ return self._zoomInButton @Slot() def zoomOut(self): """ Zooms out by a single page step. """ self._zoomSlider.triggerAction(QSlider.SliderPageStepSub) def zoomOutButton(self): """ Returns the zoom out button from the right side of this widget. :return <QToolButton> """ return self._zoomOutButton def zoomSlider(self): """ Returns the slider widget of this zoom slider. :return <QSlider> """ return self._zoomSlider def zoomStep(self): """ Returns the amount for a single step when the user clicks the zoom in/ out amount. :return <int> """ return self._zoomSlider.pageStep() x_maximum = Property(int, maximum, setMaximum) x_minimum = Property(int, minimum, setMinimum) z_zoomStep = Property(int, zoomStep, setZoomStep)
def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.setupUi(self) self.setWindowTitle('DMX Test Tool by LauerSystems') # create and setup ipcon self.ipcon = IPConnection() self.ipcon.connect(HOST, PORT) self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, self.qtcb_ipcon_enumerate.emit) self.ipcon.register_callback(IPConnection.CALLBACK_CONNECTED, self.qtcb_ipcon_connected.emit) self.dmx = BrickletDMX(UID_DMX, self.ipcon) self.label_image.setText("Started!") #Configs self.wait_for_first_read = True self.qtcb_frame_started.connect(self.cb_frame_started) self.qtcb_frame.connect(self.cb_frame) self.dmx.set_dmx_mode(BrickletDMX.DMX_MODE_MASTER) print("DMX Mode [0=Master; 1=Slave]: " + str(self.dmx.get_dmx_mode())) self.dmx.set_frame_duration(200) print("Frame Duration [ms]: " + str(self.dmx.get_frame_duration())) self.address_spinboxes = [] self.address_slider = [] print("Config Ende") for i in range(20): spinbox = QSpinBox() spinbox.setMinimum(0) spinbox.setMaximum(255) slider = QSlider(Qt.Horizontal) slider.setMinimum(0) slider.setMaximum(255) spinbox.valueChanged.connect(slider.setValue) slider.valueChanged.connect(spinbox.setValue) def get_frame_value_changed_func(i): return lambda x: self.frame_value_changed(i, x) slider.valueChanged.connect(get_frame_value_changed_func(i)) self.address_table.setCellWidget(i, 0, spinbox) self.address_table.setCellWidget(i, 1, slider) self.address_spinboxes.append(spinbox) self.address_slider.append(slider) print("Erzeuge Set: " + str(i)) self.address_table.horizontalHeader().setStretchLastSection(True) self.address_table.show() self.current_frame = [0] * 512 print(self.current_frame) self.dmx.register_callback(self.dmx.CALLBACK_FRAME_STARTED, self.qtcb_frame_started.emit) self.dmx.register_callback(self.dmx.CALLBACK_FRAME, self.qtcb_frame.emit) self.dmx.set_frame_callback_config(True, False, True, False)
class ChooseThresholdsUI(QMainWindow): def __init__(self): super().__init__() self.baseImages = [] self.SobelXTh = [0, 255] self.SobelYTh = [0, 255] self.SobelMTh = [0, 255] self.SobelATh = [0, 255] self.initUI() @pyqtSlot() def openNewFileDialog(self, index): """ @brief slot with open new file dialog """ directory = os.path.dirname(self.loadFileLine[index].text()) fileName = QFileDialog.getOpenFileName(self, 'Choose image', directory, 'All files (*)') if isinstance(fileName, tuple): # for PyQt5 if fileName[0]: self.loadFileLine[index].setText(fileName[0]) else: # for PyQt4 if fileName: self.loadFileLine[index].setText(fileName) @pyqtSlot() def loadImage(self): self.baseImages = [] for i in range(0, 4): if (i > 0): if not self.loadFileCB[i - 1].isChecked(): continue image = cv2.imread(self.loadFileLine[i].text()) if image is not None: self.baseImages.append(image) if len(self.baseImages) != 0: self.updateImage() @pyqtSlot() def sliderChange(self): self.SobelXTh[0] = self.slider1SobelX.value() self.SobelXTh[1] = self.slider2SobelX.value() self.labelSobelX.setText("SobelX th: {:03d} {:03d}".format( self.SobelXTh[0], self.SobelXTh[1])) self.SobelYTh[0] = self.slider1SobelY.value() self.SobelYTh[1] = self.slider2SobelY.value() self.labelSobelY.setText("SobelY th: {:03d} {:03d}".format( self.SobelYTh[0], self.SobelYTh[1])) self.SobelMTh[0] = self.slider1SobelM.value() self.SobelMTh[1] = self.slider2SobelM.value() self.labelSobelM.setText("SobelM th: {:03d} {:03d}".format( self.SobelMTh[0], self.SobelMTh[1])) self.SobelATh[0] = self.slider1SobelA.value() * np.pi / 510 self.SobelATh[1] = self.slider2SobelA.value() * np.pi / 510 self.labelSobelA.setText("SobelA th: {:1.3f} {:1.3f}".format( self.SobelATh[0], self.SobelATh[1])) self.updateImage() def initUI(self): # Choose file dialog loadFileBtn = QPushButton("Load files:") loadFileBtn.clicked.connect(self.loadImage) self.loadFileLine = [] loadFileDialogBtn = [] self.loadFileCB = [] for i in range(0, 4): self.loadFileLine.append(QLineEdit("")) loadFileDialogBtn.append(QPushButton("...")) loadFileDialogBtn[i].setMaximumWidth(40) if (i > 0): self.loadFileCB.append(QCheckBox()) # self.loadFileCB[i-1].stateChanged.connect(self.updateImage) loadFileDialogBtn[0].clicked.connect(lambda: self.openNewFileDialog(0)) loadFileDialogBtn[1].clicked.connect(lambda: self.openNewFileDialog(1)) loadFileDialogBtn[2].clicked.connect(lambda: self.openNewFileDialog(2)) loadFileDialogBtn[3].clicked.connect(lambda: self.openNewFileDialog(3)) loadFileDialogBtn[1].clicked.connect( lambda: self.loadFileCB[0].setChecked(True)) loadFileDialogBtn[2].clicked.connect( lambda: self.loadFileCB[1].setChecked(True)) loadFileDialogBtn[3].clicked.connect( lambda: self.loadFileCB[2].setChecked(True)) self.labelImage = QLabel() labelChannels = QLabel("Channels:") self.comboChannel0 = QComboBox() self.comboChannel0.addItems(['G', 'L', 'S']) self.comboChannel0.currentIndexChanged.connect(self.updateImage) self.comboChannel1 = QComboBox() self.comboChannel1.addItems(['G', 'L', 'S']) self.comboChannel1.currentIndexChanged.connect(self.updateImage) self.comboChannel2 = QComboBox() self.comboChannel2.addItems(['G', 'L', 'S']) self.comboChannel2.currentIndexChanged.connect(self.updateImage) labelKernels = QLabel("Kernels:") self.kernel0SB = QSpinBox() self.kernel0SB.setMinimum(1) self.kernel0SB.setMaximum(31) self.kernel0SB.setValue(15) self.kernel0SB.setSingleStep(2) self.kernel0SB.valueChanged.connect(self.updateImage) self.kernel1SB = QSpinBox() self.kernel1SB.setMinimum(1) self.kernel1SB.setMaximum(31) self.kernel1SB.setValue(15) self.kernel1SB.setSingleStep(2) self.kernel1SB.valueChanged.connect(self.updateImage) self.kernel2SB = QSpinBox() self.kernel2SB.setMinimum(1) self.kernel2SB.setMaximum(31) self.kernel2SB.setValue(15) self.kernel2SB.setSingleStep(2) self.kernel2SB.valueChanged.connect(self.updateImage) self.labelSobelX = QLabel() self.chboxSobelX0 = QCheckBox() self.chboxSobelX0.stateChanged.connect(self.updateImage) self.chboxSobelX1 = QCheckBox() self.chboxSobelX1.stateChanged.connect(self.updateImage) self.chboxSobelX2 = QCheckBox() self.chboxSobelX2.stateChanged.connect(self.updateImage) self.slider1SobelX = QSlider(Qt.Horizontal) self.slider1SobelX.setMinimum(0) self.slider1SobelX.setMaximum(255) self.slider1SobelX.setValue(20) self.slider1SobelX.valueChanged.connect(self.sliderChange) self.slider2SobelX = QSlider(Qt.Horizontal) self.slider2SobelX.setMinimum(0) self.slider2SobelX.setMaximum(255) self.slider2SobelX.setValue(100) self.slider2SobelX.valueChanged.connect(self.sliderChange) self.labelSobelY = QLabel() self.chboxSobelY0 = QCheckBox() self.chboxSobelY0.stateChanged.connect(self.updateImage) self.chboxSobelY1 = QCheckBox() self.chboxSobelY1.stateChanged.connect(self.updateImage) self.chboxSobelY2 = QCheckBox() self.chboxSobelY2.stateChanged.connect(self.updateImage) self.slider1SobelY = QSlider(Qt.Horizontal) self.slider1SobelY.setMinimum(0) self.slider1SobelY.setMaximum(255) self.slider1SobelY.setValue(20) self.slider1SobelY.valueChanged.connect(self.sliderChange) self.slider2SobelY = QSlider(Qt.Horizontal) self.slider2SobelY.setMinimum(0) self.slider2SobelY.setMaximum(255) self.slider2SobelY.setValue(100) self.slider2SobelY.valueChanged.connect(self.sliderChange) self.labelSobelM = QLabel() self.chboxSobelM0 = QCheckBox() self.chboxSobelM0.stateChanged.connect(self.updateImage) self.chboxSobelM1 = QCheckBox() self.chboxSobelM1.stateChanged.connect(self.updateImage) self.chboxSobelM2 = QCheckBox() self.chboxSobelM2.stateChanged.connect(self.updateImage) self.slider1SobelM = QSlider(Qt.Horizontal) self.slider1SobelM.setMinimum(0) self.slider1SobelM.setMaximum(255) self.slider1SobelM.setValue(30) self.slider1SobelM.valueChanged.connect(self.sliderChange) self.slider2SobelM = QSlider(Qt.Horizontal) self.slider2SobelM.setMinimum(0) self.slider2SobelM.setMaximum(255) self.slider2SobelM.setValue(100) self.slider2SobelM.valueChanged.connect(self.sliderChange) self.labelSobelA = QLabel() self.chboxSobelA0 = QCheckBox() self.chboxSobelA0.stateChanged.connect(self.updateImage) self.chboxSobelA1 = QCheckBox() self.chboxSobelA1.stateChanged.connect(self.updateImage) self.chboxSobelA2 = QCheckBox() self.chboxSobelA2.stateChanged.connect(self.updateImage) self.slider1SobelA = QSlider(Qt.Horizontal) self.slider1SobelA.setMinimum(0) self.slider1SobelA.setMaximum(255) self.slider1SobelA.setValue(int(0.7 / np.pi * 510)) self.slider1SobelA.valueChanged.connect(self.sliderChange) self.slider2SobelA = QSlider(Qt.Horizontal) self.slider2SobelA.setMinimum(0) self.slider2SobelA.setMaximum(255) self.slider2SobelA.setValue(int(1.3 / np.pi * 510)) self.slider2SobelA.valueChanged.connect(self.sliderChange) self.sliderChange() # Layouts layoutMain = QVBoxLayout() layoutMain2 = QHBoxLayout() layoutSettings = QVBoxLayout() layoutChannels = QHBoxLayout() layoutKernelSB = QHBoxLayout() layoutChboxSobelX = QHBoxLayout() layoutChboxSobelY = QHBoxLayout() layoutChboxSobelM = QHBoxLayout() layoutChboxSobelA = QHBoxLayout() layoutsChooseFile = [] for i in range(0, 4): layoutsChooseFile.append(QHBoxLayout()) if i == 0: layoutsChooseFile[i].addWidget(loadFileBtn) else: layoutsChooseFile[i].addWidget(self.loadFileCB[i - 1]) layoutsChooseFile[i].addWidget(self.loadFileLine[i]) layoutsChooseFile[i].addWidget(loadFileDialogBtn[i]) layoutMain.addLayout(layoutsChooseFile[i]) layoutMain.addLayout(layoutMain2, 1) layoutMain2.addWidget(self.labelImage, 1) layoutMain2.addLayout(layoutSettings) layoutSettings.addWidget(labelChannels) layoutSettings.addLayout(layoutChannels) layoutChannels.addWidget(self.comboChannel0) layoutChannels.addWidget(self.comboChannel1) layoutChannels.addWidget(self.comboChannel2) layoutSettings.addWidget(labelKernels) layoutSettings.addLayout(layoutKernelSB) layoutKernelSB.addWidget(self.kernel0SB) layoutKernelSB.addWidget(self.kernel1SB) layoutKernelSB.addWidget(self.kernel2SB) layoutSettings.addWidget(self.labelSobelX) layoutSettings.addLayout(layoutChboxSobelX) layoutChboxSobelX.addWidget(self.chboxSobelX0) layoutChboxSobelX.addWidget(self.chboxSobelX1) layoutChboxSobelX.addWidget(self.chboxSobelX2) layoutSettings.addWidget(self.slider1SobelX) layoutSettings.addWidget(self.slider2SobelX) layoutSettings.addWidget(self.labelSobelY) layoutSettings.addLayout(layoutChboxSobelY) layoutChboxSobelY.addWidget(self.chboxSobelY0) layoutChboxSobelY.addWidget(self.chboxSobelY1) layoutChboxSobelY.addWidget(self.chboxSobelY2) layoutSettings.addWidget(self.slider1SobelY) layoutSettings.addWidget(self.slider2SobelY) layoutSettings.addWidget(self.labelSobelM) layoutSettings.addLayout(layoutChboxSobelM) layoutChboxSobelM.addWidget(self.chboxSobelM0) layoutChboxSobelM.addWidget(self.chboxSobelM1) layoutChboxSobelM.addWidget(self.chboxSobelM2) layoutSettings.addWidget(self.slider1SobelM) layoutSettings.addWidget(self.slider2SobelM) layoutSettings.addWidget(self.labelSobelA) layoutSettings.addLayout(layoutChboxSobelA) layoutChboxSobelA.addWidget(self.chboxSobelA0) layoutChboxSobelA.addWidget(self.chboxSobelA1) layoutChboxSobelA.addWidget(self.chboxSobelA2) layoutSettings.addWidget(self.slider1SobelA) layoutSettings.addWidget(self.slider2SobelA) layoutSettings.addStretch(1) mainWidget = QWidget() mainWidget.setLayout(layoutMain) self.setCentralWidget(mainWidget) self.showMaximized() def selectChannel(self, combo, N): if combo.currentText() == 'G': im = cv2.cvtColor(self.baseImages[N], cv2.COLOR_BGR2GRAY) elif combo.currentText() == 'L': im = cv2.cvtColor(self.baseImages[N], cv2.COLOR_BGR2HLS)[:, :, 1] elif combo.currentText() == 'S': im = cv2.cvtColor(self.baseImages[N], cv2.COLOR_BGR2HLS)[:, :, 2] return im def updateOneImg(self, imN): changed = False if self.chboxSobelX0.isChecked() or self.chboxSobelY0.isChecked() or self.chboxSobelM0.isChecked() or \ self.chboxSobelA0.isChecked(): changed = True im = self.selectChannel(self.comboChannel0, imN) th = pipeline.Tresholds(im, kernel=self.kernel0SB.value()) im0 = np.ones_like(im, dtype='uint8') if self.chboxSobelX0.isChecked(): im0 = im0 & th.abs_sobel_thresh(orient='x', thresh=self.SobelXTh) if self.chboxSobelY0.isChecked(): im0 = im0 & th.abs_sobel_thresh(orient='y', thresh=self.SobelYTh) if self.chboxSobelM0.isChecked(): im0 = im0 & th.mag_thresh(thresh=self.SobelMTh) if self.chboxSobelA0.isChecked(): im0 = im0 & th.dir_threshold(thresh=self.SobelATh) else: im0 = np.zeros_like(self.baseImages[imN][:, :, 0], dtype='uint8') if self.chboxSobelX1.isChecked() or self.chboxSobelY1.isChecked() or self.chboxSobelM1.isChecked() or \ self.chboxSobelA1.isChecked(): changed = True im = self.selectChannel(self.comboChannel1, imN) th = pipeline.Tresholds(im, kernel=self.kernel1SB.value()) im1 = np.ones_like(im, dtype='uint8') if self.chboxSobelX1.isChecked(): im1 = im1 & th.abs_sobel_thresh(orient='x', thresh=self.SobelXTh) if self.chboxSobelY1.isChecked(): im1 = im1 & th.abs_sobel_thresh(orient='y', thresh=self.SobelYTh) if self.chboxSobelM1.isChecked(): im1 = im1 & th.mag_thresh(thresh=self.SobelMTh) if self.chboxSobelA1.isChecked(): im1 = im1 & th.dir_threshold(thresh=self.SobelATh) else: im1 = np.zeros_like(self.baseImages[imN][:, :, 0], dtype='uint8') if self.chboxSobelX2.isChecked() or self.chboxSobelY2.isChecked() or self.chboxSobelM2.isChecked() or \ self.chboxSobelA2.isChecked(): changed = True im = self.selectChannel(self.comboChannel2, imN) th = pipeline.Tresholds(im, kernel=self.kernel2SB.value()) im2 = np.ones_like(im, dtype='uint8') if self.chboxSobelX2.isChecked(): im2 = im2 & th.abs_sobel_thresh(orient='x', thresh=self.SobelXTh) if self.chboxSobelY2.isChecked(): im2 = im2 & th.abs_sobel_thresh(orient='y', thresh=self.SobelYTh) if self.chboxSobelM2.isChecked(): im2 = im2 & th.mag_thresh(thresh=self.SobelMTh) if self.chboxSobelA2.isChecked(): im2 = im2 & th.dir_threshold(thresh=self.SobelATh) else: im2 = np.zeros_like(self.baseImages[imN][:, :, 0], dtype='uint8') if not changed: imf = cv2.cvtColor(self.baseImages[imN], cv2.COLOR_BGR2RGB) else: imf = np.dstack((im0 * 255, im1 * 255, im2 * 255)) return imf def updateImage(self): if len(self.baseImages) == 0: return imf = [] for i in range(len(self.baseImages)): im = self.updateOneImg(i) imf.append(im) frameSize = (self.labelImage.size().width(), self.labelImage.size().height(), 3) bytesPerLine = 3 * frameSize[0] if len(self.baseImages) == 1: frameImg = cv2.resize(imf[0], frameSize[0:2]) else: frameImg = np.zeros([frameSize[1], frameSize[0], frameSize[2]], dtype='uint8') midy = frameSize[1] // 2 midx = frameSize[0] // 2 # frameImg[0:midy, 0:midx, :] = 255 frameImg[:midy, :midx, :] = cv2.resize(imf[0], (midx, midy)) frameImg[:midy, midx:midx * 2, :] = cv2.resize(imf[1], (midx, midy)) if len(self.baseImages) >= 3: frameImg[midy:midy * 2, :midx, :] = cv2.resize( imf[2], (midx, midy)) if len(self.baseImages) >= 4: frameImg[midy:midy * 2, midx:midx * 2, :] = cv2.resize(imf[3], (midx, midy)) qImg = QImage(frameImg, frameSize[0], frameSize[1], bytesPerLine, QImage.Format_RGB888) self.labelImage.setPixmap(QPixmap.fromImage(qImg))
def __init__(self,model): super(QWidget,self).__init__() if not isinstance(model,Model): raise Exception('Constructor argument of type Model expected.') self.setWindowTitle('Strandbeest simulator') # lazily simulates on full movement cycle of the strandbeest def iterateStates(): ''' Iterates over the first full movement cycle of the Strandbeest. In order to determine when the movement repeats, a heuristic is used, that stops simulating once the state vector becomes similar enough to the initial state vector. This heuristic assumes that the movement of the Strandbeest is time independent. ''' x0 = model.state() yield x0 for _ in range(2): model.increment(0.01) xi = model.state() yield xi limit = norm(xi-x0) while True: model.increment(0.01) xi = model.state() yield xi if norm(xi-x0) < limit: # <- heuristic condition for a full simulation cycle break # record simulation results record = _Record() view = _View(model,record) def recordStates(states): ''' The _Canvas uses the states of the simulation to display movement curves of the nodes. For that purposes the simulated states are stored to the model in the record.states list. In order to notify the _View of newly simulated states, all callables in the record.changeListeners list are notified, with the new state vector as argument. ''' for x in states: record.states.append(x) record.velocities.append( model.v(x,t=None) ) record.times.append( model.t ) for listener in record.changeListeners: listener(x) yield x del record.changeListeners def recordSceenshots(statesLoop): ''' A little utility i created to be able to generate GIFs from the simulation. Saves screenshots from the current view of every 10th simulation step. ''' i,j = 0,0 for x in statesLoop: if i < 2*943 and 0 == i % 10: img = QPixmap.grabWidget(self) img = img.scaled(640,500,transformMode = Qt.SmoothTransformation) img.save('data/img%(j)d.jpg' % locals(),'jpg') j+=1 i += 1 yield x statesLoop = iterateStates() statesLoop = recordStates(statesLoop) statesLoop = itertools.cycle(statesLoop) # statesLoop = recordSceenshots(statesLoop) def tick(): ''' Advances the view by one tick (not neccessarily the simulation) ''' model.setState( next(statesLoop) ) # <- in the first cycle this statement is redundant tick() timer = QTimer() timer.timeout.connect(tick) speedLabel = QLabel('? * Realtime') speedLabel.resize(speedLabel.sizeHint()) speedLabel.setToolTip('Simulation speed [ticks/sec.].') speedSlider = QSlider(Qt.Horizontal) speedSlider.resize(speedSlider.sizeHint()) speedSlider.setMinimum(0) speedSlider.setMaximum(6) speedSlider.setTickPosition(QSlider.TicksBelow) def tpsChange(value): # <- called whenever ticks/sec. change ''' Changes the number of simulation ticks per second. ''' value = 2**(value-2) speedLabel.setText( '%(value)6.2f * Realtime' % locals() ) timer.setInterval(10/value) speedSlider.valueChanged[int].connect(tpsChange) speedSlider.setValue(4) def startStopClick(): startStopClick.running ^= True if startStopClick.running: timer.start() startStop.setText('Stop') else: timer.stop() startStop.setText('Start') startStop = QPushButton('Start/Stop') startStop.resize(startStop.sizeHint()) startStop.setToolTip('Start the simulation.') startStop.clicked.connect(startStopClick) startStopClick.running = True startStopClick() grid = QGridLayout(self) grid.addWidget(startStop,0,0) grid.addWidget(speedSlider,0,1) grid.addWidget(speedLabel,0,2) grid.addWidget(view,1,0,1,3)
class GUI(QWidget): def __init__(self, parent=None): global f f = open(filename, "a") f.write("Widget init.\n") f.close() QWidget.__init__(self, parent, Qt.WindowStaysOnTopHint) self.__setup_gui__(self) self._flag = False self._change = False f = open(filename, "a") f.write("End of widget init.\n") f.close() def closeEvent(self, event): reply = QMessageBox.question(self, "Confirm", "Are you sure You want to quit?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: event.accept() else: event.ignore() def __setup_gui__(self, Dialog): global f f = open(filename, "a") f.write("Setup of gui.\n") f.close() Dialog.setObjectName("Dialog") Dialog.resize(270, 145) self.setWindowTitle("Map Layer") screen = QDesktopWidget().screenGeometry() size = self.geometry() self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2) self.Render = QPushButton("Render", Dialog) self.Render.setGeometry(QRect(85, 90, 100, 25)) self.Render.setObjectName("Render") self.comboBox = QComboBox(Dialog) self.comboBox.setGeometry(QRect(100, 34, 115, 18)) self.comboBox.setEditable(False) self.comboBox.setMaxVisibleItems(11) self.comboBox.setInsertPolicy(QComboBox.InsertAtBottom) self.comboBox.setObjectName("comboBox") self.comboBox.addItems([ "Google Roadmap", "Google Terrain", "Google Satellite", "Google Hybrid", "Yahoo Roadmap", "Yahoo Satellite", "Yahoo Hybrid", "Bing Roadmap", "Bing Satellite", "Bing Hybrid", "Open Street Maps" ]) self.comboBox.setCurrentIndex(10) self.label1 = QLabel("Source:", Dialog) self.label1.setGeometry(QRect(55, 35, 35, 16)) self.label1.setObjectName("label1") self.slider = QSlider(Dialog) self.slider.setOrientation(Qt.Horizontal) self.slider.setMinimum(1) self.slider.setMaximum(12) self.slider.setValue(4) self.slider.setGeometry(QRect(110, 61, 114, 16)) self.label2 = QLabel("Quality: " + str(self.slider.value()), Dialog) self.label2.setGeometry(QRect(47, 61, 54, 16)) self.label2.setObjectName("label2") self.doubleSpinBox = QDoubleSpinBox(Dialog) self.doubleSpinBox.setGeometry(QRect(160, 5, 40, 20)) self.doubleSpinBox.setDecimals(0) self.doubleSpinBox.setObjectName("doubleSpinBox") self.doubleSpinBox.setMinimum(10.0) self.doubleSpinBox.setValue(20.0) self.doubleSpinBox.setEnabled(False) self.checkBox = QCheckBox("Auto refresh", Dialog) self.checkBox.setGeometry(QRect(50, 6, 100, 20)) self.checkBox.setLayoutDirection(Qt.RightToLeft) self.checkBox.setObjectName("checkBox") self.progressBar = QProgressBar(Dialog) self.progressBar.setGeometry(QRect(5, 130, 260, 10)) self.progressBar.setProperty("value", 0) self.progressBar.setTextVisible(False) self.progressBar.setObjectName("progressBar") self.progressBar.setVisible(False) QObject.connect(self.Render, SIGNAL("clicked()"), Dialog.__repaint__) QMetaObject.connectSlotsByName(Dialog) QObject.connect(self.slider, SIGNAL("valueChanged(int)"), self.__update_slider_label__) QObject.connect(self.comboBox, SIGNAL("activated(int)"), self.__combobox_changed__) self.timerRepaint = QTimer() QObject.connect(self.checkBox, SIGNAL("clicked()"), self.__activate_timer__) QObject.connect(self.timerRepaint, SIGNAL("timeout()"), self.__on_timer__) f = open(filename, "a") f.write("End of setup of gui.\n") f.close() def __combobox_changed__(self): self._change = True def __activate_timer__(self): self.doubleSpinBox.setEnabled(self.checkBox.isChecked()) if self.checkBox.isChecked(): self.timerRepaint.start(self.doubleSpinBox.value() * 1000) self.Render.setEnabled(False) if _progress == 0: self.__repaint__() else: self.timerRepaint.stop() self.Render.setEnabled(True) def __get_net_size__(self): global f f = open(filename, "a") f.write("Geting net size...\n") f.close() if not os.path.exists(Paths["Screenshot"]): Visum.Graphic.Screenshot(Paths["Screenshot"]) size = Image.open(Paths["Screenshot"]).size f = open(filename, "a") f.write("Read net size:" + str(size) + ".\n") f.close() return size def __on_timer__(self): global _paramGlobal self._flag = False Visum.Graphic.MaximizeNetWindow() param = _paramGlobal _paramGlobal = Visum.Graphic.GetWindow() shift = abs((param[0] - _paramGlobal[0]) / (param[2] - param[0])) zoom = abs((param[2] - param[0]) / (_paramGlobal[2] - _paramGlobal[0]) - 1) print _windowSizeGlobal if _windowSizeGlobal[2:4] != Visum.Graphic.GetMainWindowPos()[2:4]: self.__get_net_size__() self._flag = True elif shift > 0.4 or zoom > 0.2: self._flag = True if self._flag or self._change and _progress == 0: self.__repaint__() self._change = False def __update_slider_label__(self, value): self.label2.setText("Quality: " + str(value)) self._change = True def __update_progress_bar__(self): if _progress != 0: self.progressBar.setVisible(True) self.progressBar.setValue(_progress) else: self.progressBar.setVisible(False) def __rebuild_paths__(self): global Paths Paths["Images"] = [] list = os.listdir(Paths["ScriptFolder"]) imageList = [] for i in range(len(list)): if list[i][-3:] == "png": imageList.append(list[i]) for i in range(len(imageList)): try: Visum.Graphic.Backgrounds.ItemByKey(imageList[i]) Paths["Images"].append(Paths["ScriptFolder"] + "\\" + imageList[i]) except: pass def __repaint__(self): global _progress, f if len(Visum.Graphic.Backgrounds.GetAll) != len(Paths["Images"]): self.__rebuild_paths__() if _progress == 0: f = open(filename, "a") f.write("Doing repaint...\n") f.close() QWebSettings.clearMemoryCaches() timer = QTimer() timer.start(100) QObject.connect(timer, SIGNAL("timeout()"), self.__update_progress_bar__) Main(self.comboBox.currentIndex(), Visum.Graphic.GetWindow(), self.slider.value() / 4.0, self.__get_net_size__()) Visum.Graphic.Draw() self.__update_progress_bar__() _progress = 0 QTimer().singleShot(1500, self.__update_progress_bar__) f = open(filename, "a") f.write("End of doing repaint.\n") f.close()
class FeeSelectionDialog(ArmoryDialog): ############################################################################# def __init__(self, parent, main, cs_callback, get_csstate): super(FeeSelectionDialog, self).__init__(parent, main) #Button Label self.lblButtonFee = QLabelButton("") #get default values flatFee = self.main.getSettingOrSetDefault("Default_Fee", MIN_TX_FEE) flatFee = coin2str(flatFee, maxZeros=1).strip() fee_byte = str( self.main.getSettingOrSetDefault("Default_FeeByte", MIN_FEE_BYTE)) blocksToConfirm = self.main.getSettingOrSetDefault(\ "Default_FeeByte_BlocksToConfirm", NBLOCKS_TO_CONFIRM) feeStrategy = str(self.main.getSettingOrSetDefault(\ "Default_FeeByte_Strategy", FEEBYTE_CONSERVATIVE)) self.coinSelectionCallback = cs_callback self.getCoinSelectionState = get_csstate self.validAutoFee = True isSmartFee = True try: feeEstimate, isSmartFee, errorMsg = self.getFeeByteFromNode( blocksToConfirm, feeStrategy) except: feeEstimate = "N/A" self.validAutoFee = False defaultCheckState = \ self.main.getSettingOrSetDefault("FeeOption", DEFAULT_FEE_TYPE) #flat free def setFlatFee(): def callbck(): return self.selectType('FlatFee') return callbck def updateLbl(): self.updateCoinSelection() self.radioFlatFee = QRadioButton(self.tr("Flat Fee (BTC)")) self.edtFeeAmt = QLineEdit(flatFee) self.edtFeeAmt.setFont(GETFONT('Fixed')) self.edtFeeAmt.setMinimumWidth(tightSizeNChar(self.edtFeeAmt, 6)[0]) self.edtFeeAmt.setMaximumWidth(tightSizeNChar(self.edtFeeAmt, 12)[0]) self.connect(self.radioFlatFee, SIGNAL('clicked()'), setFlatFee()) self.connect(self.edtFeeAmt, SIGNAL('textChanged(QString)'), updateLbl) frmFlatFee = QFrame() frmFlatFee.setFrameStyle(STYLE_RAISED) layoutFlatFee = QGridLayout() layoutFlatFee.addWidget(self.radioFlatFee, 0, 0, 1, 1) layoutFlatFee.addWidget(self.edtFeeAmt, 0, 1, 1, 1) frmFlatFee.setLayout(layoutFlatFee) #fee/byte def setFeeByte(): def callbck(): return self.selectType('FeeByte') return callbck self.radioFeeByte = QRadioButton(self.tr("Fee/Byte (Satoshi/Byte)")) self.edtFeeByte = QLineEdit(fee_byte) self.edtFeeByte.setFont(GETFONT('Fixed')) self.edtFeeByte.setMinimumWidth(tightSizeNChar(self.edtFeeByte, 6)[0]) self.edtFeeByte.setMaximumWidth(tightSizeNChar(self.edtFeeByte, 12)[0]) self.connect(self.radioFeeByte, SIGNAL('clicked()'), setFeeByte()) self.connect(self.edtFeeByte, SIGNAL('textChanged(QString)'), updateLbl) frmFeeByte = QFrame() frmFeeByte.setFrameStyle(STYLE_RAISED) layoutFeeByte = QGridLayout() layoutFeeByte.addWidget(self.radioFeeByte, 0, 0, 1, 1) layoutFeeByte.addWidget(self.edtFeeByte, 0, 1, 1, 1) frmFeeByte.setLayout(layoutFeeByte) #auto fee/byte if isSmartFee: frmAutoFeeByte = self.setupSmartAutoFeeByteUI(\ feeEstimate, blocksToConfirm, feeStrategy) else: frmAutoFeeByte = self.setupLegacyAutoFeeByteUI(\ feeEstimate, blocksToConfirm) #adjust and close self.btnClose = QPushButton(self.tr('Close')) self.connect(self.btnClose, SIGNAL('clicked()'), self.accept) self.checkBoxAdjust = QCheckBox(self.tr('Adjust fee/byte for privacy')) self.checkBoxAdjust.setChecked(\ self.main.getSettingOrSetDefault('AdjustFee', True)) self.connect(self.checkBoxAdjust, SIGNAL('clicked()'), updateLbl) frmClose = makeHorizFrame(\ [self.checkBoxAdjust, 'Stretch', self.btnClose], STYLE_NONE) #main layout layout = QGridLayout() layout.addWidget(frmAutoFeeByte, 0, 0, 1, 4) layout.addWidget(frmFeeByte, 2, 0, 1, 4) layout.addWidget(frmFlatFee, 4, 0, 1, 4) layout.addWidget(frmClose, 5, 0, 1, 4) self.setLayout(layout) self.setWindowTitle(self.tr('Select Fee Type')) self.selectType(defaultCheckState) self.setFocus() ############################################################################# def setupLegacyAutoFeeByteUI(self, feeEstimate, blocksToConfirm): def setAutoFeeByte(): def callbck(): return self.selectType('Auto') return callbck def updateLbl(): self.updateCoinSelection() def feeByteToStr(feeByte): try: self.feeByte = feeByte return "<u>%.1f</u>" % feeByte except: self.feeByte = -1 if isinstance(feeByte, str): return feeByte else: return "N/A" radioButtonTxt = self.tr("Fee rate from node (sat/Byte): ") if not self.validAutoFee: radioButtonTxt = self.tr("Failed to fetch fee/byte from node") self.radioAutoFeeByte = QRadioButton(radioButtonTxt) self.lblAutoFeeByte = QLabel(feeByteToStr(feeEstimate)) self.lblAutoFeeByte.setFont(GETFONT('Fixed')) self.lblAutoFeeByte.setMinimumWidth( tightSizeNChar(self.lblAutoFeeByte, 6)[0]) self.lblAutoFeeByte.setMaximumWidth( tightSizeNChar(self.lblAutoFeeByte, 12)[0]) self.sliderAutoFeeByte = QSlider(Qt.Horizontal, self) self.sliderAutoFeeByte.setMinimum(2) self.sliderAutoFeeByte.setMaximum(6) self.sliderAutoFeeByte.setValue(blocksToConfirm) self.lblSlider = QLabel() def getSliderLabelTxt(): return self.tr("Blocks to confirm: %1").arg(\ unicode(self.sliderAutoFeeByte.value())) def updateAutoFeeByte(): blocksToConfirm = self.sliderAutoFeeByte.value() try: feeEstimate, version, err = \ self.getFeeByteFromNode(blocksToConfirm, FEEBYTE_CONSERVATIVE) except: feeEstimate = "N/A" self.lblSlider.setText(getSliderLabelTxt()) self.lblAutoFeeByte.setText(feeByteToStr(feeEstimate)) updateLbl() self.lblSlider.setText(getSliderLabelTxt()) self.connect(self.radioAutoFeeByte, SIGNAL('clicked()'), setAutoFeeByte()) self.sliderAutoFeeByte.valueChanged.connect(updateAutoFeeByte) self.sliderAutoFeeByte.setEnabled(False) frmAutoFeeByte = QFrame() frmAutoFeeByte.setFrameStyle(STYLE_RAISED) layoutAutoFeeByte = QGridLayout() layoutAutoFeeByte.addWidget(self.radioAutoFeeByte, 0, 0, 1, 1) layoutAutoFeeByte.addWidget(self.lblAutoFeeByte, 0, 1, 1, 1) layoutAutoFeeByte.addWidget(self.lblSlider, 1, 0, 1, 2) layoutAutoFeeByte.addWidget(self.sliderAutoFeeByte, 2, 0, 1, 2) frmAutoFeeByte.setLayout(layoutAutoFeeByte) if not self.validAutoFee: frmAutoFeeByte.setEnabled(False) return frmAutoFeeByte ############################################################################# def setupSmartAutoFeeByteUI(self, feeEstimate, blocksToConfirm, strat): def setAutoFeeByte(): def callbck(): return self.selectType('Auto') return callbck stratList = [FEEBYTE_CONSERVATIVE, FEEBYTE_ECONOMICAL] def updateLbl(): self.updateCoinSelection() def getStrategyString(): try: cbIndex = self.comboStrat.currentIndex() return stratList[cbIndex] except: return FEEBYTE_CONSERVATIVE def feeByteToStr(feeByte): try: self.feeByte = feeByte return "<u>%.1f</u>" % feeByte except: self.feeByte = -1 if isinstance(feeByte, str): return feeByte else: return "N/A" radioButtonTxt = self.tr("Fee rate from node (sat/Byte): ") if not self.validAutoFee: radioButtonTxt = self.tr("Failed to fetch fee/byte from node") self.radioAutoFeeByte = QRadioButton(radioButtonTxt) self.lblAutoFeeByte = QLabel(feeByteToStr(feeEstimate)) self.lblAutoFeeByte.setFont(GETFONT('Fixed')) self.lblAutoFeeByte.setMinimumWidth( tightSizeNChar(self.lblAutoFeeByte, 6)[0]) self.lblAutoFeeByte.setMaximumWidth( tightSizeNChar(self.lblAutoFeeByte, 12)[0]) self.sliderAutoFeeByte = QSlider(Qt.Horizontal, self) self.sliderAutoFeeByte.setMinimum(2) self.sliderAutoFeeByte.setMaximum(100) self.sliderAutoFeeByte.setValue(blocksToConfirm) self.lblSlider = QLabel() self.lblStrat = QLabel(self.tr("Profile:")) self.ttStart = self.main.createToolTipWidget( self.tr(''' <u>Fee Estimation Profiles:</u><br><br> <b>CONSERVATIVE:</b> Short term estimate. More reactive to current changes in the mempool. Use this estimate if you want a high probability of getting your transaction mined quickly. <br><br> <b>ECONOMICAL:</b> Long term estimate. Ignores short term changes to the mempool. Use this profile if you want low fees and can tolerate swings in the projected confirmation window. <br><br> The estimate profiles may not diverge until your node has gathered enough data from the network to refine its predictions. Refer to the \"estimatesmartfee\" section in the Bitcoin Core 0.15 changelog for more informations. ''')) self.comboStrat = QComboBox() currentIndex = 0 for i in range(len(stratList)): self.comboStrat.addItem(stratList[i]) if stratList[i] == strat: currentIndex = i self.comboStrat.setCurrentIndex(currentIndex) def getSliderLabelTxt(): return self.tr("Blocks to confirm: %1").arg(\ unicode(self.sliderAutoFeeByte.value())) def updateAutoFeeByte(): blocksToConfirm = self.sliderAutoFeeByte.value() strategy = getStrategyString() try: feeEstimate, version, err = \ self.getFeeByteFromNode(blocksToConfirm, strategy) except: feeEstimate = "N/A" self.lblSlider.setText(getSliderLabelTxt()) self.lblAutoFeeByte.setText(feeByteToStr(feeEstimate)) updateLbl() def stratComboChange(): updateAutoFeeByte() self.lblSlider.setText(getSliderLabelTxt()) self.connect(self.radioAutoFeeByte, SIGNAL('clicked()'), setAutoFeeByte()) self.sliderAutoFeeByte.valueChanged.connect(updateAutoFeeByte) self.sliderAutoFeeByte.setEnabled(False) self.connect(self.comboStrat, SIGNAL('currentIndexChanged(int)'), stratComboChange) frmAutoFeeByte = QFrame() frmAutoFeeByte.setFrameStyle(STYLE_RAISED) layoutAutoFeeByte = QGridLayout() layoutAutoFeeByte.addWidget(self.radioAutoFeeByte, 0, 0, 1, 2) layoutAutoFeeByte.addWidget(self.lblAutoFeeByte, 0, 2, 1, 2) layoutAutoFeeByte.addWidget(self.lblSlider, 1, 0, 1, 1) layoutAutoFeeByte.addWidget(self.sliderAutoFeeByte, 2, 0, 1, 4) layoutAutoFeeByte.addWidget(self.lblStrat, 3, 0, 1, 1) layoutAutoFeeByte.addWidget(self.comboStrat, 3, 1, 1, 2) layoutAutoFeeByte.addWidget(self.ttStart, 3, 3, 1, 1) frmAutoFeeByte.setLayout(layoutAutoFeeByte) if not self.validAutoFee: frmAutoFeeByte.setEnabled(False) return frmAutoFeeByte ############################################################################# def getFeeByteFromNode(self, blocksToConfirm, strategy): try: feeEstimateResult = estimateFee(blocksToConfirm, strategy) return feeEstimateResult.val_ * 100000, \ feeEstimateResult.isSmart_, \ feeEstimateResult.error_ except: self.validAutoFee = False return "N/A", False, "" ############################################################################# def selectType(self, strType): self.radioFlatFee.setChecked(False) self.radioFeeByte.setChecked(False) self.radioAutoFeeByte.setChecked(False) self.sliderAutoFeeByte.setEnabled(False) if strType == 'FlatFee': self.radioFlatFee.setChecked(True) elif strType == 'FeeByte': self.radioFeeByte.setChecked(True) elif strType == 'Auto': if not self.validAutoFee: self.radioFeeByte.setChecked(True) else: self.radioAutoFeeByte.setChecked(True) self.sliderAutoFeeByte.setEnabled(True) self.updateCoinSelection() self.updateLabelButton() ############################################################################# def updateCoinSelection(self): try: self.coinSelectionCallback() except: self.updateLabelButton() ############################################################################# def getLabelButton(self): return self.lblButtonFee ############################################################################# def updateLabelButtonText(self, txSize, flatFee, fee_byte): txSize = str(txSize) if txSize != 'N/A': txSize += " B" if flatFee != 'N/A': flatFee = coin2str(flatFee, maxZeros=0).strip() flatFee += " BTC" if not isinstance(fee_byte, str): fee_byte = '%.2f' % fee_byte lblStr = "Size: %s, Fee: %s" % (txSize, flatFee) if fee_byte != 'N/A': lblStr += " (%s sat/B)" % fee_byte self.lblButtonFee.setText(lblStr) ############################################################################# def updateLabelButton(self, reset=False): try: if reset: raise Exception() txSize, flatFee, feeByte = self.getCoinSelectionState() self.updateLabelButtonText(txSize, flatFee, feeByte) except: self.updateLabelButtonText('N/A', 'N/A', 'N/A') ############################################################################# def resetLabel(self): self.updateLabelButton(True) ############################################################################# def getFeeData(self): fee = 0 fee_byte = 0 if self.radioFlatFee.isChecked(): flatFeeText = str(self.edtFeeAmt.text()) fee = str2coin(flatFeeText) elif self.radioFeeByte.isChecked(): fee_byteText = str(self.edtFeeByte.text()) fee_byte = float(fee_byteText) elif self.radioAutoFeeByte.isChecked(): fee_byte = self.feeByte adjust_fee = self.checkBoxAdjust.isChecked() return fee, fee_byte, adjust_fee ############################################################################# def setZeroFee(self): self.edtFeeAmt.setText('0') self.selectType('FlatFee')
class QtSlider(QtControl, ProxySlider): """ A Qt implementation of an Enaml ProxySlider. """ #: A reference to the widget created by the proxy. widget = Typed(QSlider) #: Cyclic notification guard flags. _guard = Int(0) #-------------------------------------------------------------------------- # Initialization API #-------------------------------------------------------------------------- def create_widget(self): """ Create the underlying QSlider widget. """ self.widget = QSlider(self.parent_widget()) def init_widget(self): """ Initialize the underlying widget. """ super(QtSlider, self).init_widget() d = self.declaration self.set_minimum(d.minimum) self.set_maximum(d.maximum) self.set_value(d.value) self.set_orientation(d.orientation) self.set_page_step(d.page_step) self.set_single_step(d.single_step) self.set_tick_interval(d.tick_interval) self.set_tick_position(d.tick_position) self.set_tracking(d.tracking) self.widget.valueChanged.connect(self.on_value_changed) #-------------------------------------------------------------------------- # Signal Handlers #-------------------------------------------------------------------------- def on_value_changed(self): """ Send the 'value_changed' action to the Enaml widget when the slider value has changed. """ if not self._guard & VALUE_FLAG: self._guard |= VALUE_FLAG try: self.declaration.value = self.widget.value() finally: self._guard &= ~VALUE_FLAG #-------------------------------------------------------------------------- # ProxySlider API #-------------------------------------------------------------------------- def set_maximum(self, maximum): """ Set the maximum value of the underlying widget. """ self.widget.setMaximum(maximum) def set_minimum(self, minimum): """ Set the minimum value of the underlying widget. """ self.widget.setMinimum(minimum) def set_value(self, value): """ Set the value of the underlying widget. """ if not self._guard & VALUE_FLAG: self._guard |= VALUE_FLAG try: self.widget.setValue(value) finally: self._guard &= ~VALUE_FLAG def set_page_step(self, page_step): """ Set the page step of the underlying widget. """ self.widget.setPageStep(page_step) def set_single_step(self, single_step): """ Set the single step of the underlying widget. """ self.widget.setSingleStep(single_step) def set_tick_interval(self, interval): """ Set the tick interval of the underlying widget. """ self.widget.setTickInterval(interval) def set_tick_position(self, tick_position): """ Set the tick position of the underlying widget. """ self.widget.setTickPosition(TICK_POSITION[tick_position]) def set_orientation(self, orientation): """ Set the orientation of the underlying widget. """ self.widget.setOrientation(ORIENTATION[orientation]) def set_tracking(self, tracking): """ Set the tracking of the underlying widget. """ self.widget.setTracking(tracking)
class View (QFrame): def __init__ (self, name, graph_view, scene, parent=None): QFrame.__init__(self, parent) self.graph_view = graph_view self.graph_view.setView0 (self) self.scene = scene self.setFrameStyle (QFrame.Sunken | QFrame.StyledPanel) self.font = QFont() self.font.setPointSize(10) self.graphicsView = CustomGraphicsView () self.graphicsView.setRenderHint (QPainter.Antialiasing, True) self.graphicsView.setDragMode (QGraphicsView.RubberBandDrag) self.graphicsView.setViewportUpdateMode (QGraphicsView.SmartViewportUpdate) #self.graphicsView.setMouseTracking(True) # toolbox definition + group page definition sizePolicy = QSizePolicy (QSizePolicy.Fixed, QSizePolicy.Expanding) self.setObjectName ('Form') self.resize (900, 1000) self._toolBox = QToolBox (self) self._toolBox.setGeometry (QRect (0, 0, 131, 301)) self._toolBox.setFont (self.font) self._toolBox.setObjectName ('_toolBox') self._toolBox.setCursor (Qt.PointingHandCursor) self.groupCluster = QWidget () self.groupCluster.setGeometry (QRect(0, 0, 91, 241)) self.groupCluster.setObjectName ('groupCluster') self.groupLineEdit = QLineEdit (self.groupCluster) self.groupLineEdit.setGeometry (QRect (2, 20, 60, 16)) self.groupLineEdit.setObjectName ('groupLineEdit') self.label = QLabel (self.groupCluster) self.label.setGeometry (QRect (4, 6, 62, 16)) self.label.setFont (self.font) self.label.setObjectName ('label') self.label_2 = QLabel (self.groupCluster) self.label_2.setGeometry (QRect (4, 40, 62, 16)) self.label_2.setFont (self.font) self.label_2.setObjectName ('label_2') self.groupLineEdit_2 = QLineEdit (self.groupCluster) self.groupLineEdit_2.setGeometry (QRect(2, 54, 60, 16)) self.groupLineEdit_2.setObjectName ('groupLineEdit_2') self.pushButton = QPushButton (self.groupCluster) self.pushButton.setGeometry (QRect (2, 90, 60, 16)) self.pushButton.setFont (self.font) self.pushButton.setObjectName ('pushButton') self._toolBox.addItem (self.groupCluster, '') self._toolBox.setItemText (self._toolBox.indexOf (self.groupCluster), QApplication.translate ("Form", "Group", None, QApplication.UnicodeUTF8)) self.setWindowTitle (QApplication.translate ("Form", "Form", None, QApplication.UnicodeUTF8)) self.label.setText (QApplication.translate ("Form", "name group", None, QApplication.UnicodeUTF8)) self.label_2.setText (QApplication.translate ("Form", "group id", None, QApplication.UnicodeUTF8)) self.pushButton.setText (QApplication.translate ("Form", "add cluster", None, QApplication.UnicodeUTF8)) self._toolBox.setSizePolicy (sizePolicy) self._toolBox.setEnabled (False) # adding the first cluster to the toolbox - a cluster is always present! self._cluster_page_list = [] self.connect (self.pushButton, SIGNAL ("clicked()"), self.addCluster) # connect the 'add-cluster' button to the method that taps into the model for cluster addition. self.connect (self.graph_view.getComm(), SIGNAL ("addCluster_MSignal(int)"), self.addClusterPage) self.connect (self.graph_view.getComm(), SIGNAL ("deleteCluster_MSignal(int)"), self.removeClusterPage) self.connect (self.graph_view.getComm(), SIGNAL ("updateClusterName_MSignal(int, QString)"), self.updateClusterViewName) self.addCluster () # add the first cluster. At least one cluster needs to be always present. self.disableAllClusterPagesDeleteButton() # since there's only one cluster page, the delete button is disabled. #size = self.style ().pixelMetric (QStyle.PM_ToolBarIconSize) iconSize = QSize (16, 16) #QSize (size, size) zoomInIcon = QToolButton () zoomInIcon.setCursor (Qt.PointingHandCursor) zoomInIcon.setAutoRepeat (True) zoomInIcon.setAutoRepeatInterval (33) zoomInIcon.setAutoRepeatDelay (0) zoomInIcon.setIconSize (iconSize) zoomOutIcon = QToolButton () zoomOutIcon.setCursor (Qt.PointingHandCursor) zoomOutIcon.setAutoRepeat (True) zoomOutIcon.setAutoRepeatInterval (33) zoomOutIcon.setAutoRepeatDelay (0) zoomOutIcon.setIconSize (iconSize) self.zoomSlider = QSlider () self.zoomSlider.setCursor (Qt.PointingHandCursor) self.zoomSlider.setMinimum (200) self.zoomSlider.setMaximum (280) self.zoomSlider.setValue (240) self.zoomSlider.setTickPosition (QSlider.TicksRight) # Zoom slider layout zoomSliderLayout = QVBoxLayout () zoomSliderLayout.addWidget (zoomInIcon) zoomSliderLayout.addWidget (self.zoomSlider) zoomSliderLayout.addWidget (zoomOutIcon) self.printOutBtn = QPushButton() self.printOutBtn.setText ("print") self.printOutBtn.setFont (self.font) self.printOutBtn.setEnabled (False) self.newJADESceneBtn = QPushButton() self.newJADESceneBtn.setText ("new") self.newJADESceneBtn.setFont (self.font) self.newJADESceneBtn.setEnabled (False) self.loadNodesDescrpBtn = QPushButton() self.loadNodesDescrpBtn.setText ("load Nodes Description") self.loadNodesDescrpBtn.setFont (self.font) self.loadNodesDescrpBtn.setEnabled (True) self.graphLoadBtn = QPushButton() self.graphLoadBtn.setText ("load") self.graphLoadBtn.setFont (self.font) self.graphLoadBtn.setEnabled (False) self.graphSaveBtn = QPushButton() self.graphSaveBtn.setText ("save") self.graphSaveBtn.setFont (self.font) self.graphSaveBtn.setEnabled (False) self.resetButton = QToolButton () self.resetButton.setText ("r") self.resetButton.setFont (self.font) self.resetButton.setEnabled (False) self.message_bar = QLineEdit () self.message_bar.setGeometry (QRect (0, 0, 190, 12)) self.message_bar.setObjectName ('message_bar') self.message_bar.setText ('Node description file, please.') self.message_bar.setFont (self.font) self.message_bar.setEnabled (True) self.message_bar.setReadOnly (True) self.spacer = QSpacerItem (30, 20, QSizePolicy.Fixed, QSizePolicy.Fixed ); # Label layout labelLayout = QHBoxLayout () self.label = QLabel (name) self.label.setFont (self.font) labelLayout.addWidget (self.loadNodesDescrpBtn) labelLayout.addWidget (self.newJADESceneBtn) labelLayout.addWidget (self.graphLoadBtn) labelLayout.addWidget (self.graphSaveBtn) labelLayout.addWidget (self.printOutBtn) labelLayout.addItem (self.spacer) labelLayout.addWidget (self.message_bar) #labelLayout.addWidget (self.label) labelLayout.addStretch () # top layout topLayout = QGridLayout () topLayout.setHorizontalSpacing (0) topLayout.setVerticalSpacing (0) topLayout.addLayout (labelLayout, 0, 1) topLayout.addWidget (self._toolBox, 1, 0) topLayout.addWidget (self.resetButton, 0, 2) topLayout.addWidget (self.graphicsView, 1, 1) topLayout.addLayout (zoomSliderLayout, 1, 2) self.setLayout (topLayout) self.connect (self.resetButton, SIGNAL ("clicked()"), self.resetView) self.connect (self.zoomSlider, SIGNAL ("valueChanged(int)"), self.setupMatrix) self.connect (self.graphicsView.verticalScrollBar (), SIGNAL ("valueChanged(int)"), self.setResetButtonEnabled) self.connect (self.graphicsView.horizontalScrollBar (), SIGNAL ("valueChanged(int)"), self.setResetButtonEnabled) self.connect (zoomInIcon, SIGNAL ("clicked()"), self.zoomIn) self.connect (zoomOutIcon, SIGNAL ("clicked()"), self.zoomOut) self.setupMatrix () self.printer = QPrinter (QPrinter.HighResolution) self.prev_selection_list = [] self.isClusterRemovalOverridden = False def setMessageBarText (self, text): self.message_bar.setText (text) def enableControls (self): self.printOutBtn.setEnabled (True) self.newJADESceneBtn.setEnabled (True) self.graphLoadBtn.setEnabled (True) self.graphSaveBtn.setEnabled (True) self._toolBox.setEnabled (True) def disableControls (self): self.printOutBtn.setEnabled (False) self.newJADESceneBtn.setEnabled (False) self.graphLoadBtn.setEnabled (False) self.graphSaveBtn.setEnabled (False) self._toolBox.setEnabled (False) def setGraphicsViewCSSBackground (self): self.graphicsView.setStyleSheet('background-color: qlineargradient(spread:pad, x1:0, y1:1, x2:0, y2:0, stop:0 rgba(125, 125, 135, 255), stop:1 rgba(215, 215, 215, 255));\ncolor: rgb(255, 255, 255);') def selectionChanged (self): current_selection_list = self.scene.selectedItems () list_of_unselected_items = [item for item in self.prev_selection_list if item not in current_selection_list] # un-mark items in list_of_unselected_items for item in list_of_unselected_items: if self.graph_view.isTag (item) == True: item.switchToUnSelectedStateColour () # mark items in current_selection_list for item in current_selection_list: if self.graph_view.isTag (item) == True: item.switchToSelectedStateColour () self.prev_selection_list = current_selection_list # - - - cluster-specific methods - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - def addCluster (self): self.graph_view.delegateClusterAddition () def addClusterPage (self, new_cluster_id): self.enableAllClusterPagesDeleteButton () # enable all the cluster page's delete buttons (as I can be bothered to go look for the one that got previously disabled) tmp_w = QWidget () tmp_l = QLabel (tmp_w) tmp_e = QLineEdit (tmp_w) tmp_b = QPushButton (tmp_w) self._cluster_page_list.append ([new_cluster_id, tmp_w, tmp_l, tmp_e, tmp_b]) tmp_w.setGeometry (QRect (0, 0, 131, 241)) tmp_w.setObjectName ('Cluster_' + str (new_cluster_id)) tmp_l.setGeometry (QRect (4, 6, 62, 16)) tmp_l.setFont (self.font) tmp_l.setObjectName ('label_' + str (new_cluster_id)) tmp_e.setGeometry (QRect (2, 20, 60, 16)) tmp_e.setObjectName ('groupLineEdit_' + str (new_cluster_id)) tmp_b.setGeometry (QRect (2, 50, 60, 16)) tmp_b.setFont (self.font) tmp_b.setObjectName ('pushButton_' + str (new_cluster_id)) self._toolBox.addItem (tmp_w, 'cluster_page_'+str(new_cluster_id)) self._toolBox.setItemText (self._toolBox.indexOf (tmp_w), QApplication.translate ('Form', 'C_'+str(new_cluster_id), None, QApplication.UnicodeUTF8)) tmp_l.setText (QApplication.translate ("Form", "name cluster", None, QApplication.UnicodeUTF8)) tmp_b.setText (QApplication.translate ("Form", "delete", None, QApplication.UnicodeUTF8)) self._toolBox.setCurrentIndex (new_cluster_id) QMetaObject.connectSlotsByName (self) # hook up the delete button (use a closure) receiver = lambda : self.removeCluster (new_cluster_id) self.connect (tmp_b, SIGNAL ("clicked()"), receiver) # connect the 'add cluster' button to the method generating new cluster pages. receiver2 = lambda value : self.updateClusterModelName (new_cluster_id, value) self.connect (tmp_e, SIGNAL ("textChanged(QString)"), receiver2) def removeAllClusters (self): copy_list = list (self._cluster_page_list) self.isClusterRemovalOverridden = True for item in copy_list: self.removeCluster (item[0]) self.graph_view.initGraphViewLists () self.graph_view.initComm () self.graph_view.initModel () self._cluster_page_list = [] self.addCluster () # add the first cluster. At least one cluster needs to be always present. self.isClusterRemovalOverridden = False # remove override def removeCluster (self, cluster_id): self.graph_view.delegateClusterRemoval (cluster_id) def removeClusterPage (self, cluster_id): threshold = 1 if self.isClusterRemovalOverridden==False else 0 qq = len(self._cluster_page_list) if qq > threshold: for i in range (qq-1, -1, -1): if int(self._cluster_page_list[i][0]) == cluster_id: self._toolBox.removeItem (self._toolBox.indexOf(self._cluster_page_list[i][1])) del self._cluster_page_list[i] break if len(self._cluster_page_list) == 1: self.disableAllClusterPagesDeleteButton () def disableAllClusterPagesDeleteButton (self): if len(self._cluster_page_list) > 0: for item in self._cluster_page_list: item[4].setEnabled (False) def enableAllClusterPagesDeleteButton (self): if len(self._cluster_page_list) > 0: for item in self._cluster_page_list: item[4].setEnabled (True) def updateClusterModelName (self, cluster_id, text): self.graph_view.delegateUpdateClusterName (cluster_id, text) def updateClusterViewName (self, cluster_id, text): if len(self._cluster_page_list) > 0: for item in self._cluster_page_list: if int(item[0]) == cluster_id: item[3].setText (str(text)) def updateCurrentClusterNodeList (self, node): # fetch the current cluster's id. curr_widget = self._toolBox.currentWidget() for item in self._cluster_page_list: if item[1] == curr_widget: # delegate cluster node list update. self.graph_view.delegateClusterNodeListUpdate (item[0], node) break def getCurrentClusterIndex (self): return self._toolBox.currentIndex () # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - def getGraphicsView (self): return self.graphicsView def resetView (self): self.zoomSlider.setValue (250) self.setupMatrix () self.graphicsView.ensureVisible (QRectF (0, 0, 0, 0)) self.resetButton.setEnabled (False) def setResetButtonEnabled (self): self.resetButton.setEnabled (True) def setupMatrix (self): scale = pow (2.0, (self.zoomSlider.value () - 250) / 50.0) matrix = QMatrix () matrix.scale (scale, scale) self.graphicsView.setMatrix (matrix) self.setResetButtonEnabled () def printOutGraph (self): qqq = QPainter (self.printer) self.graphicsView.render(qqq) def importNodesDescription (self): aa = QFileDialog (self).getOpenFileName() if aa != QString (u''): # it can be equal to QString(u'') when the user presses the Escape key, so in that circumstance, nothing is returned. self.graph_view.setNodesDescription (open(aa).read()) def resetScene (self): self.removeAllClusters () self.resetView () def exportGraph (self): aa = QFileDialog (self).getSaveFileName () if aa != QString (u''): # it can be equal to QString(u'') when the user presses the Escape key, so in that circumstance, nothing is returned. file0 = open (aa, 'w') file0.write (self.graph_view.delegateExport ()) file0.close () print '\n*** file exported.\n' def importGraph (self): aa = QFileDialog (self).getOpenFileName () if aa != QString (u''): # it can be equal to QString(u'') when the user presses the Escape key, so in that circumstance, nothing is returned. file0 = open (aa, 'r') XML_content = file0.read() file0.close () self.graph_view.delegateImport (XML_content) print '\n*** file imported.\n' # zoom slider def zoomIn (self) : self.zoomSlider.setValue (self.zoomSlider.value() + 1) def zoomOut (self) : self.zoomSlider.setValue (self.zoomSlider.value() - 1) def getZoomSlider (self): return self.zoomSlider def setToolboxCSSColorScheme (self, css): self._toolBox.setStyleSheet (css) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - def wireViewItemsUp (self): self.connect (self.newJADESceneBtn, SIGNAL ("clicked()"), self.resetScene) self.connect (self.loadNodesDescrpBtn, SIGNAL ("clicked()"), self.importNodesDescription) self.connect (self.graphSaveBtn, SIGNAL ("clicked()"), self.exportGraph) self.connect (self.graphLoadBtn, SIGNAL ("clicked()"), self.importGraph) self.connect (self.printOutBtn, SIGNAL ("clicked()"), self.printOutGraph)
class GraphGui(QWidget): def __init__(self, G=None, pos=None, parent=None): QWidget.__init__(self, parent) self.scene = GraphGraphicsScene(G, pos, self) self.view = QGraphicsView(self.scene, self) self.button = QPushButton("Quit", self) self.nodeButton = QPushButton("Node", self) self.edgeButton = QPushButton("Edge", self) self.addButton = QPushButton("Add", self) self.deleteButton = QPushButton("Delete", self) self.printButton = QPushButton("Print", self) self.eulerButton = QPushButton("Euler", self) self.generateFullButton = QPushButton("Full", self) self.generateHalfButton = QPushButton("Half", self) self.infoButton = QPushButton("Info", self) # self.testButton = QPushButton('Test', self) self.nodesInputLabel = QLabel("Nodes", self) self.edgesInputLabel = QLabel("Edges", self) self.saveButton = QPushButton("Save", self) self.loadButton = QPushButton("Load", self) self.saveAsButton = QPushButton("SaveAs", self) self.bridgeButton = QPushButton("Bridge", self) self.stepSlider = QSlider(self) self.cursorLabelX = QLabel("X:", self) self.cursorLabelY = QLabel("Y:", self) self.nodeNumberLabel = QLabel("Nr:", self) self.fileLabel = QLabel("File:", self) self.nodeInfo = QLabel("N:", self) self.edgeInfo = QLabel("E:", self) self.eulerInfo = QLabel("None", self) # self.fileInput = QLineEdit(self) self.fileInput = QLabel("", self) self.euler = Euler() self.eulerStep = 0 self.eulerPath = [] validator = QIntValidator(0, 10000) self.nodesNumberInput = QLineEdit(self) self.nodesNumberInput.setValidator(validator) self.edgesNumberInput = QLineEdit(self) self.edgesNumberInput.setValidator(validator) self.cursorLabelX.setMinimumSize(150, 25) self.cursorLabelY.setMinimumSize(150, 25) self.nodeNumberLabel.setMinimumSize(150, 25) self.labelsGroup = QVBoxLayout() self.labelsGroup.addWidget(self.cursorLabelX) self.labelsGroup.addWidget(self.cursorLabelY) self.labelsGroup.addWidget(self.nodeNumberLabel) HEIGHT = 50 WIDTH = 50 self.nodeButton.setFixedSize(HEIGHT, WIDTH) self.edgeButton.setFixedSize(HEIGHT, WIDTH) self.addButton.setFixedSize(HEIGHT, WIDTH) self.button.setFixedSize(HEIGHT, WIDTH) self.deleteButton.setFixedSize(HEIGHT, WIDTH) self.printButton.setFixedSize(HEIGHT, WIDTH) self.eulerButton.setFixedSize(HEIGHT, WIDTH) self.generateFullButton.setFixedSize(HEIGHT, WIDTH) self.generateHalfButton.setFixedSize(HEIGHT, WIDTH) self.saveButton.setFixedSize(HEIGHT, WIDTH) self.loadButton.setFixedSize(HEIGHT, WIDTH) self.saveAsButton.setFixedSize(HEIGHT, WIDTH) self.infoButton.setFixedSize(HEIGHT, WIDTH) self.bridgeButton.setFixedSize(HEIGHT, WIDTH) self.nodesNumberInput.setFixedSize(HEIGHT * 2, 28) self.edgesNumberInput.setFixedSize(HEIGHT * 2, 28) self.stepSlider.setFixedSize(HEIGHT * 2, 28) # self.testButton.setFixedSize(HEIGHT, WIDTH) self.disableSlider() self.stepSlider.setOrientation(Qt.Horizontal) horizontal_expanding_spacer1 = QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum) self.fileGroup = QHBoxLayout() self.fileGroup.addWidget(self.fileLabel) self.fileGroup.addWidget(self.fileInput) self.fileGroup.addItem(horizontal_expanding_spacer1) self.actionsButtonGroup = QHBoxLayout() self.actionsButtonGroup.addWidget(self.addButton) self.actionsButtonGroup.addWidget(self.deleteButton) self.actionsButtonGroup.addWidget(self.printButton) self.actionsButtonGroup.addWidget(self.eulerButton) self.actionsButtonGroup.addWidget(self.generateFullButton) self.actionsButtonGroup.addWidget(self.generateHalfButton) self.actionsButtonGroup.addWidget(self.saveButton) self.actionsButtonGroup.addWidget(self.loadButton) self.actionsButtonGroup.addWidget(self.saveAsButton) self.actionsButtonGroup.addWidget(self.infoButton) self.actionsButtonGroup.addWidget(self.bridgeButton) # self.actionsButtonGroup.addWidget(self.testButton) self.actionsButtonGroup.addWidget(self.button) self.topGroup = QVBoxLayout() self.topGroup.addItem(self.fileGroup) self.topGroup.addItem(self.actionsButtonGroup) horizontal_expanding_spacer = QSpacerItem(10, 10, QSizePolicy.Expanding, QSizePolicy.Minimum) self.actionsButtonGroup.addItem(horizontal_expanding_spacer) self.actionsButtonGroup.addItem(self.labelsGroup) self.modeButtonGroup = QVBoxLayout() self.modeButtonGroup.addWidget(self.nodeButton) self.modeButtonGroup.addWidget(self.edgeButton) self.modeButtonGroup.addWidget(self.nodesInputLabel) self.modeButtonGroup.addWidget(self.nodesNumberInput) self.modeButtonGroup.addWidget(self.edgesInputLabel) self.modeButtonGroup.addWidget(self.edgesNumberInput) self.modeButtonGroup.addWidget(self.stepSlider) vertical_expanding_spacer = QSpacerItem(10, 10, QSizePolicy.Minimum, QSizePolicy.Expanding) self.modeButtonGroup.addItem(vertical_expanding_spacer) self.infoGroup = QVBoxLayout() self.infoGroup.addWidget(self.edgeInfo) self.infoGroup.addWidget(self.nodeInfo) self.infoGroup.addWidget(self.eulerInfo) self.modeButtonGroup.addItem(self.infoGroup) self.button.clicked.connect(QCoreApplication.instance().quit) self.addButton.clicked.connect(self.add) self.deleteButton.clicked.connect(self.delete) self.nodeButton.clicked.connect(self.nodeButtonEvent) self.edgeButton.clicked.connect(self.edgeButtonEvent) self.printButton.clicked.connect(self.printButtonEvent) self.eulerButton.clicked.connect(self.findEulerPath) self.generateFullButton.clicked.connect(self.generateFull) self.generateHalfButton.clicked.connect(self.generateHalf) # self.testButton.clicked.connect(self.scene.changeColor) self.saveAsButton.clicked.connect(self.saveAsFile) self.saveButton.clicked.connect(self.saveFile) self.loadButton.clicked.connect(self.loadFile) self.scene.cursorPositionSignal.connect(self.setLabels) self.scene.nodeNumberSignal.connect(self.setLabelNumber) self.stepSlider.sliderMoved.connect(self.setEulerStep) self.bridgeButton.clicked.connect(self.findBridges) self.infoButton.clicked.connect(self.setInfo) self.view.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) layoutH = QHBoxLayout() layoutH.addWidget(self.view) layoutH.addItem(self.modeButtonGroup) layoutV = QVBoxLayout() layoutV.addItem(self.topGroup) layoutV.addItem(layoutH) self.setLayout(layoutV) self.setWindowTitle("Example") self.scene.setSceneRect(0, 0, 1, 1) self.view.setMouseTracking(True) self.showMaximized() self.graphFile = GraphFile("file.txt") def findBridges(self): bridges = self.euler.find_bridges(self.scene.G) print bridges def generate(self, h_or_f): generator = Generator() nodesNumberStr = self.nodesNumberInput.text() edgesNumberStr = self.edgesNumberInput.text() if nodesNumberStr == "" or edgesNumberStr == "": return nodeNumber = int(nodesNumberStr) edgesNumber = int(edgesNumberStr) G = None if h_or_f == "FULL": G = generator.generate_full_euler_graph(nodeNumber, edgesNumber) elif h_or_f == "HALF": G = generator.generate_half_euler_graph(nodeNumber, edgesNumber) if G is not None: self.scene.clear() self.scene.drawGraph(G) self.setInfo() def setInfo(self): self.edgeInfo.setText("E: " + str(len(self.scene.G.edges()))) self.nodeInfo.setText("N: " + str(len(self.scene.G.nodes()))) info, odds = self.euler.checkGraph(self.scene.G) self.eulerInfo.setText(info) def generateHalf(self): self.generate("HALF") def generateFull(self): self.generate("FULL") def add(self): self.scene.add() self.setInfo() def delete(self): self.scene.delete() self.setInfo() def findEulerPath(self): eulerPath = self.euler.start(self.scene.getGraph()) print eulerPath if eulerPath is not None and len(eulerPath) > 0: self.enableSlider(len(eulerPath)) self.eulerPath = eulerPath def setEulerStep(self, stepNum): self.scene.setColorForAllEdges(QColor.fromRgb(0, 0, 0)) if stepNum > 0: for i in range(stepNum): node1 = self.eulerPath[i] node2 = self.eulerPath[i + 1] self.scene.setColorForEdge(node1, node2, QColor.fromRgb(0, 255, 0)) def resizeEvent(self, event): w = self.view.width() - 10 h = self.view.height() - 10 transform = QTransform.fromScale(w, h) self.view.setTransform(transform) QWidget.resizeEvent(self, event) def enableSlider(self, maximum): self.stepSlider.setEnabled(True) self.stepSlider.setMinimum(0) self.stepSlider.setMaximum(maximum - 1) def disableSlider(self): self.stepSlider.setDisabled(False) def setLabels(self, x, y): self.cursorLabelX.setText("X:" + str(x)) self.cursorLabelY.setText("Y:" + str(y)) def setLabelNumber(self, number): self.nodeNumberLabel.setText("Nr:" + str(number)) def nodeButtonEvent(self): if self.scene.getMode() == "None": self.scene.changeMode("Node") self.nodeButton.setFlat(True) elif self.scene.getMode() == "Node": self.nodeButton.setFlat(False) self.scene.changeMode("None") elif self.scene.getMode() == "Edge": self.edgeButton.setFlat(False) self.scene.changeMode("Node") self.nodeButton.setFlat(True) def edgeButtonEvent(self): if self.scene.getMode() == "None": self.scene.changeMode("Edge") self.edgeButton.setFlat(True) elif self.scene.getMode() == "Edge": self.scene.changeMode("None") self.edgeButton.setFlat(False) elif self.scene.getMode() == "Node": self.scene.changeMode("Edge") self.nodeButton.setFlat(False) self.edgeButton.setFlat(True) def printButtonEvent(self): print self.scene.G.nodes() print self.scene.G.edges() def saveFile(self): if self.graphFile.path != "": self.graphFile.save(self.scene.G, self.scene.getPos()) else: self.saveAsFile() def saveAsFile(self): path = QFileDialog.getSaveFileName(self, "Open Graph", ".", "Text files (*.txt)") self.setFilePath(path) self.graphFile.save(self.scene.G, self.scene.getPos()) def loadFile(self): path = QFileDialog.getOpenFileName(self, "Open Graph", ".", "Text files (*.txt)") self.setFilePath(path) (G, pos, n, n) = self.graphFile.load() self.scene.clear() self.scene.drawGraph(G, pos) self.setInfo() def setFilePath(self, path): self.graphFile.path = path self.fileInput.setText(path)
class PreferencesDialogBase(QDialog): def __init__(self, parent, app): flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint QDialog.__init__(self, parent, flags) self.app = app self._setupUi() self.connect(self.filterHardnessSlider, SIGNAL("valueChanged(int)"), self.filterHardnessLabel.setNum) self.connect(self.buttonBox, SIGNAL('clicked(QAbstractButton*)'), self.buttonClicked) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) def _setupScanTypeBox(self, labels): self.scanTypeHLayout = QHBoxLayout() self.scanTypeLabel = QLabel(self) self.scanTypeLabel.setText(tr("Scan Type:")) self.scanTypeLabel.setMinimumSize(QSize(100, 0)) self.scanTypeLabel.setMaximumSize(QSize(100, 16777215)) self.scanTypeHLayout.addWidget(self.scanTypeLabel) self.scanTypeComboBox = QComboBox(self) for label in labels: self.scanTypeComboBox.addItem(label) self.scanTypeHLayout.addWidget(self.scanTypeComboBox) self.widgetsVLayout.addLayout(self.scanTypeHLayout) def _setupFilterHardnessBox(self): self.filterHardnessHLayout = QHBoxLayout() self.filterHardnessLabel = QLabel(self) self.filterHardnessLabel.setText(tr("Filter Hardness:")) self.filterHardnessLabel.setMinimumSize(QSize(0, 0)) self.filterHardnessHLayout.addWidget(self.filterHardnessLabel) self.filterHardnessVLayout = QVBoxLayout() self.filterHardnessVLayout.setSpacing(0) self.filterHardnessHLayoutSub1 = QHBoxLayout() self.filterHardnessHLayoutSub1.setSpacing(12) self.filterHardnessSlider = QSlider(self) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.filterHardnessSlider.sizePolicy().hasHeightForWidth()) self.filterHardnessSlider.setSizePolicy(sizePolicy) self.filterHardnessSlider.setMinimum(1) self.filterHardnessSlider.setMaximum(100) self.filterHardnessSlider.setTracking(True) self.filterHardnessSlider.setOrientation(Qt.Horizontal) self.filterHardnessHLayoutSub1.addWidget(self.filterHardnessSlider) self.filterHardnessLabel = QLabel(self) self.filterHardnessLabel.setText("100") self.filterHardnessLabel.setMinimumSize(QSize(21, 0)) self.filterHardnessHLayoutSub1.addWidget(self.filterHardnessLabel) self.filterHardnessVLayout.addLayout(self.filterHardnessHLayoutSub1) self.filterHardnessHLayoutSub2 = QHBoxLayout() self.filterHardnessHLayoutSub2.setContentsMargins(-1, 0, -1, -1) self.moreResultsLabel = QLabel(self) self.moreResultsLabel.setText(tr("More Results")) self.filterHardnessHLayoutSub2.addWidget(self.moreResultsLabel) spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.filterHardnessHLayoutSub2.addItem(spacerItem) self.fewerResultsLabel = QLabel(self) self.fewerResultsLabel.setText(tr("Fewer Results")) self.filterHardnessHLayoutSub2.addWidget(self.fewerResultsLabel) self.filterHardnessVLayout.addLayout(self.filterHardnessHLayoutSub2) self.filterHardnessHLayout.addLayout(self.filterHardnessVLayout) def _setupBottomPart(self): # The bottom part of the pref panel is always the same in all editions. self.fontSizeLabel = QLabel(tr("Font size:")) self.fontSizeSpinBox = QSpinBox() self.fontSizeSpinBox.setMinimum(5) self.widgetsVLayout.addLayout(horizontalWrap([self.fontSizeLabel, self.fontSizeSpinBox, None])) self.languageLabel = QLabel(tr("Language:"), self) self.languageComboBox = QComboBox(self) for lang in SUPPORTED_LANGUAGES: self.languageComboBox.addItem(LANGNAMES[lang]) self.widgetsVLayout.addLayout(horizontalWrap([self.languageLabel, self.languageComboBox, None])) self.copyMoveLabel = QLabel(self) self.copyMoveLabel.setText(tr("Copy and Move:")) self.widgetsVLayout.addWidget(self.copyMoveLabel) self.copyMoveDestinationComboBox = QComboBox(self) self.copyMoveDestinationComboBox.addItem(tr("Right in destination")) self.copyMoveDestinationComboBox.addItem(tr("Recreate relative path")) self.copyMoveDestinationComboBox.addItem(tr("Recreate absolute path")) self.widgetsVLayout.addWidget(self.copyMoveDestinationComboBox) self.customCommandLabel = QLabel(self) self.customCommandLabel.setText(tr("Custom Command (arguments: %d for dupe, %r for ref):")) self.widgetsVLayout.addWidget(self.customCommandLabel) self.customCommandEdit = QLineEdit(self) self.widgetsVLayout.addWidget(self.customCommandEdit) def _setupAddCheckbox(self, name, label, parent=None): if parent is None: parent = self cb = QCheckBox(parent) cb.setText(label) setattr(self, name, cb) def _setupPreferenceWidgets(self): # Edition-specific pass def _setupUi(self): self.setWindowTitle(tr("Preferences")) self.resize(304, 263) self.setSizeGripEnabled(False) self.setModal(True) self.mainVLayout = QVBoxLayout(self) self.widgetsVLayout = QVBoxLayout() self._setupPreferenceWidgets() self.mainVLayout.addLayout(self.widgetsVLayout) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok|QDialogButtonBox.RestoreDefaults) self.mainVLayout.addWidget(self.buttonBox) if (not ISOSX) and (not ISLINUX): self.mainVLayout.removeWidget(self.ignoreHardlinkMatches) self.ignoreHardlinkMatches.setHidden(True) def _load(self, prefs, setchecked): # Edition-specific pass def _save(self, prefs, ischecked): # Edition-specific pass def load(self, prefs=None): if prefs is None: prefs = self.app.prefs self.filterHardnessSlider.setValue(prefs.filter_hardness) self.filterHardnessLabel.setNum(prefs.filter_hardness) setchecked = lambda cb, b: cb.setCheckState(Qt.Checked if b else Qt.Unchecked) setchecked(self.mixFileKindBox, prefs.mix_file_kind) setchecked(self.useRegexpBox, prefs.use_regexp) setchecked(self.removeEmptyFoldersBox, prefs.remove_empty_folders) setchecked(self.ignoreHardlinkMatches, prefs.ignore_hardlink_matches) setchecked(self.debugModeBox, prefs.debug_mode) self.copyMoveDestinationComboBox.setCurrentIndex(prefs.destination_type) self.customCommandEdit.setText(prefs.custom_command) self.fontSizeSpinBox.setValue(prefs.tableFontSize) try: langindex = SUPPORTED_LANGUAGES.index(self.app.prefs.language) except ValueError: langindex = 0 self.languageComboBox.setCurrentIndex(langindex) self._load(prefs, setchecked) def save(self): prefs = self.app.prefs prefs.filter_hardness = self.filterHardnessSlider.value() ischecked = lambda cb: cb.checkState() == Qt.Checked prefs.mix_file_kind = ischecked(self.mixFileKindBox) prefs.use_regexp = ischecked(self.useRegexpBox) prefs.remove_empty_folders = ischecked(self.removeEmptyFoldersBox) prefs.ignore_hardlink_matches = ischecked(self.ignoreHardlinkMatches) prefs.debug_mode = ischecked(self.debugModeBox) prefs.destination_type = self.copyMoveDestinationComboBox.currentIndex() prefs.custom_command = str(self.customCommandEdit.text()) prefs.tableFontSize = self.fontSizeSpinBox.value() lang = SUPPORTED_LANGUAGES[self.languageComboBox.currentIndex()] oldlang = self.app.prefs.language if oldlang not in SUPPORTED_LANGUAGES: oldlang = 'en' if lang != oldlang: QMessageBox.information(self, "", tr("dupeGuru has to restart for language changes to take effect.")) self.app.prefs.language = lang self._save(prefs, ischecked) #--- Events def buttonClicked(self, button): role = self.buttonBox.buttonRole(button) if role == QDialogButtonBox.ResetRole: self.resetToDefaults()
class OpencvCameraTestWidget(QWidget): available_resolutions = { "160x120": [160, 120], "176x144": [176, 144], "320x240": [320, 240], "352x288": [352, 288], "640x480": [640, 480], "960x720": [960, 720], "1280x960": [1280, 960] } def __init__(self, parent=None, capture=None, widget=None): super(OpencvCameraTestWidget, self).__init__(parent) self.main_layout = QVBoxLayout(self) self.main_layout.setSizeConstraint(QLayout.SetFixedSize) if capture is None: self.capture = cv2.VideoCapture(0) else: self.capture = capture if widget is None: self.camera_widget = QImageWidget() self.main_layout.addWidget(self.camera_widget) self.camera_ret = 0 self.raw_camera_image = None # cv2.namedWindow("image") self.camera_timer = QTimer() self.camera_timer.timeout.connect(self.grab_video) self.camera_timer.start(1000 / 24) self.brightness_layout = QHBoxLayout() self.brightness_label = QLabel("Brightness: ") self.brightness_layout.addWidget(self.brightness_label) self.brightness_value_label = QLabel("") self.brightness_value_label.setMinimumWidth(30) self.brightness_slider = QSlider(Qt.Horizontal) self.brightness_slider.setFocusPolicy(Qt.StrongFocus) self.brightness_slider.setTickPosition(QSlider.TicksBothSides) self.brightness_slider.setMinimum(-10) self.brightness_slider.setMaximum(110) self.brightness_slider.setValue(20) self.brightness_slider.setTickPosition(QSlider.TicksBelow) self.brightness_slider.setTickInterval(10) self.brightness_slider.valueChanged.connect(self.set_brightness) self.brightness_layout.addWidget(self.brightness_slider) self.brightness_layout.addWidget(self.brightness_value_label) self.main_layout.addLayout(self.brightness_layout) self.contrast_layout = QHBoxLayout() self.contrast_label = QLabel("Contrast: ") self.contrast_layout.addWidget(self.contrast_label) self.contrast_value_label = QLabel("") self.contrast_value_label.setMinimumWidth(30) self.contrast_slider = QSlider(Qt.Horizontal) self.contrast_slider.setFocusPolicy(Qt.StrongFocus) self.contrast_slider.setTickPosition(QSlider.TicksBothSides) self.contrast_slider.setMinimum(-10) self.contrast_slider.setMaximum(110) self.contrast_slider.setValue(20) self.contrast_slider.setTickPosition(QSlider.TicksBelow) self.contrast_slider.setTickInterval(10) self.contrast_slider.valueChanged.connect(self.set_contrast) self.contrast_layout.addWidget(self.contrast_slider) self.contrast_layout.addWidget(self.contrast_value_label) self.main_layout.addLayout(self.contrast_layout) self.exposure_layout = QHBoxLayout() self.exposure_label = QLabel("Exposure: ") self.exposure_layout.addWidget(self.exposure_label) self.exposure_value_label = QLabel("") self.exposure_value_label.setMinimumWidth(30) self.exposure_slider = QSlider(Qt.Horizontal) self.exposure_slider.setFocusPolicy(Qt.StrongFocus) self.exposure_slider.setTickPosition(QSlider.TicksBothSides) self.exposure_slider.setMinimum(-10) self.exposure_slider.setMaximum(110) self.exposure_slider.setValue(20) self.exposure_slider.setTickPosition(QSlider.TicksBelow) self.exposure_slider.setTickInterval(10) self.exposure_slider.valueChanged.connect(self.set_exposure) self.exposure_layout.addWidget(self.exposure_slider) self.exposure_layout.addWidget(self.exposure_value_label) self.main_layout.addLayout(self.exposure_layout) self.iso_layout = QHBoxLayout() self.iso_label = QLabel("ISO: ") self.iso_layout.addWidget(self.iso_label) self.iso_value_label = QLabel("") self.iso_value_label.setMinimumWidth(30) self.iso_slider = QSlider(Qt.Horizontal) self.iso_slider.setFocusPolicy(Qt.StrongFocus) self.iso_slider.setTickPosition(QSlider.TicksBothSides) self.iso_slider.setMinimum(-10) self.iso_slider.setMaximum(110) self.iso_slider.setValue(20) self.iso_slider.setTickPosition(QSlider.TicksBelow) self.iso_slider.setTickInterval(10) self.iso_slider.valueChanged.connect(self.set_iso) self.iso_layout.addWidget(self.iso_slider) self.iso_layout.addWidget(self.iso_value_label) self.main_layout.addLayout(self.iso_layout) self.auto_exposure_label = QLabel("AutoExposure: ") self.auto_exposure_checkbox = QCheckBox("AutoExposure: ") self.exposure_layout.addWidget(self.auto_exposure_checkbox) self.auto_exposure_checkbox.stateChanged.connect( self.set_auto_exposure) self.resolutions_combo = QComboBox() self.resolutions_combo.addItems(self.available_resolutions.keys()) self.main_layout.addWidget(self.resolutions_combo) self.resolutions_combo.currentIndexChanged[str].connect( self.set_resolution) def set_brightness(self, value): self.capture.set(cv2.CAP_PROP_BRIGHTNESS, value / 100.0) self.brightness_value_label.setText(str(value / 100.0)) def set_contrast(self, value): self.capture.set(cv2.CAP_PROP_CONTRAST, value / 100.0) self.contrast_value_label.setText(str(value / 100.0)) def set_exposure(self, value): self.capture.set(cv2.CAP_PROP_EXPOSURE, value / 100.0) self.exposure_value_label.setText(str(value / 100.0)) def set_iso(self, value): self.capture.set(cv2.CAP_PROP_ISO_SPEED, value / 100.0) self.exposure_value_label.setText(str(value / 100.0)) def set_auto_exposure(self, value): if value > 0: self.capture.set(cv2.CAP_PROP_AUTO_EXPOSURE, 1) else: self.capture.set(cv2.CAP_PROP_AUTO_EXPOSURE, 0.25) def set_resolution(self, string): if str(string) in self.available_resolutions: height = self.available_resolutions[str(string)][0] width = self.available_resolutions[str(string)][1] self.capture.set(cv2.CAP_PROP_FRAME_HEIGHT, height) self.capture.set(cv2.CAP_PROP_FRAME_WIDTH, width) def grab_video(self): # print "grab video" self.camera_ret, self.raw_camera_image = self.capture.read() if self.camera_ret: self.raw_camera_image = cv2.cvtColor(self.raw_camera_image, cv2.COLOR_BGR2RGB) self.camera_widget.set_opencv_image(self.raw_camera_image)
def __init__(self, *args): COMCUPluginBase.__init__(self, BrickletDMX, *args) self.setupUi(self) self.dmx = self.device self.wait_for_first_read = True self.dmx_overview = DMXOverview(self) self.layout_dmx_overview.insertWidget(1, self.dmx_overview) self.qtcb_frame_started.connect(self.cb_frame_started) self.qtcb_frame.connect(self.cb_frame) self.mode_combobox.currentIndexChanged.connect(self.mode_changed) self.frame_duration_spinbox.valueChanged.connect( self.frame_duration_changed) self.address_spinboxes = [] self.address_slider = [] for i in range(512): spinbox = QSpinBox() spinbox.setMinimum(0) spinbox.setMaximum(255) slider = QSlider(Qt.Horizontal) slider.setMinimum(0) slider.setMaximum(255) spinbox.valueChanged.connect(slider.setValue) slider.valueChanged.connect(spinbox.setValue) def get_frame_value_changed_func(i): return lambda x: self.frame_value_changed(i, x) slider.valueChanged.connect(get_frame_value_changed_func(i)) self.address_table.setCellWidget(i, 0, spinbox) self.address_table.setCellWidget(i, 1, slider) self.address_spinboxes.append(spinbox) self.address_slider.append(slider) self.address_table.horizontalHeader().setStretchLastSection(True) self.address_table.show() self.current_frame = [0] * 512 self.com_led_off_action = QAction('Off', self) self.com_led_off_action.triggered.connect( lambda: self.dmx.set_communication_led_config( BrickletDMX.COMMUNICATION_LED_CONFIG_OFF)) self.com_led_on_action = QAction('On', self) self.com_led_on_action.triggered.connect( lambda: self.dmx.set_communication_led_config( BrickletDMX.COMMUNICATION_LED_CONFIG_ON)) self.com_led_show_heartbeat_action = QAction('Show Heartbeat', self) self.com_led_show_heartbeat_action.triggered.connect( lambda: self.dmx.set_communication_led_config( BrickletDMX.COMMUNICATION_LED_CONFIG_SHOW_HEARTBEAT)) self.com_led_show_communication_action = QAction('Show Com', self) self.com_led_show_communication_action.triggered.connect( lambda: self.dmx.set_communication_led_config( BrickletDMX.COMMUNICATION_LED_CONFIG_SHOW_COMMUNICATION)) self.extra_configs += [(1, 'Com LED:', [ self.com_led_off_action, self.com_led_on_action, self.com_led_show_heartbeat_action, self.com_led_show_communication_action ])] self.error_led_off_action = QAction('Off', self) self.error_led_off_action.triggered.connect( lambda: self.dmx.set_error_led_config(BrickletDMX. ERROR_LED_CONFIG_OFF)) self.error_led_on_action = QAction('On', self) self.error_led_on_action.triggered.connect( lambda: self.dmx.set_error_led_config(BrickletDMX. ERROR_LED_CONFIG_ON)) self.error_led_show_heartbeat_action = QAction('Show Heartbeat', self) self.error_led_show_heartbeat_action.triggered.connect( lambda: self.dmx.set_error_led_config( BrickletDMX.ERROR_LED_CONFIG_SHOW_HEARTBEAT)) self.error_led_show_error_action = QAction('Show Error', self) self.error_led_show_error_action.triggered.connect( lambda: self.dmx.set_error_led_config(BrickletDMX. ERROR_LED_CONFIG_SHOW_ERROR)) self.extra_configs += [(1, 'Error LED:', [ self.error_led_off_action, self.error_led_on_action, self.error_led_show_heartbeat_action, self.error_led_show_error_action ])]
class Slider(QWidget): def __init__( self, caption, default_value, minimum_value=1, maximum_value=60, single_step=1, page_step=6, caption_size=None, unit="", time=False, tooltip="", ): QWidget.__init__(self) self.value = default_value self.unit = unit self.time = time description = QLabel(caption) description.setWordWrap(True) description.setToolTip(tooltip) if caption_size: description.setMaximumWidth(caption_size) self.slider = QSlider(Qt.Horizontal) self.slider.setMaximum(maximum_value) self.slider.setMinimum(minimum_value) self.slider.setSingleStep(single_step) self.slider.setPageStep(page_step) self.slider.setToolTip(tooltip) # self.slider.setTickInterval(2) # self.slider.setTickPosition(QSlider.TicksBelow) self.slider.valueChanged.connect(self.__on_change) self.value_label = QLabel() hbox = QHBoxLayout() hbox.addWidget(description) hbox.addWidget(self.slider) hbox.addWidget(self.value_label) hbox.setMargin(0) self.setLayout(hbox) self.setContentsMargins(5, 0, 5, 0) self.slider.setValue(self.value) self.__on_change(self.value) def __on_change(self, value): # FIXME: Fill with spaces to reach the maximum length self.value = value unit = self.unit if self.time: minutes = timedelta(minutes=self.value) date = datetime(1, 1, 1) + minutes text = "%02dh %02dm" % (date.hour, date.minute) else: text = "%s %s" % (self.value, self.unit) self.value_label.setText(text) def get_value(self): return int(self.slider.value())
class Tool(QToolBar): def __init__(self,parent): QToolBar.__init__(self,parent) self.parent = parent self.action_NewProject = QAction(Icons.newprj, 'Project', self) self.action_NewProject.triggered.connect(self.parent.treeWidget.newProject) self.action_NewProject.setToolTip("Create a New Project") self.action_Open = QAction(Icons.open, 'Open', self) self.action_Open.triggered.connect(self.parent.fileOpen) self.action_Open.setToolTip("Open File") self.action_Save = QAction(Icons.save, 'Save', self) self.action_Save.setShortcut('Ctrl+S') self.action_Save.triggered.connect(self.parent.fileSave) self.action_Save.setToolTip("Save Current File") self.action_SaveAll = QAction(Icons.saveall, 'SaveAll', self) self.action_SaveAll.setShortcut('Ctrl+A') self.action_SaveAll.triggered.connect(self.parent.fileSaveAll) self.action_SaveAll.setToolTip("Save All Files") self.action_Build = QAction(Icons.thread_view, 'Build', self) self.action_Build.setShortcut('Ctrl+B') self.action_Build.triggered.connect(self.parent.build_project) self.action_Debug = QAction(Icons.debug_exec, 'Debug', self) self.action_Refresh = QAction(Icons.refresh_tab, 'Refresh', self) self.action_Refresh.triggered.connect(self.parent.treeWidget.refreshCurrentProject) self.action_Run = QAction(Icons.run, 'Run', self) self.action_Run.setShortcut('Ctrl+R') self.action_Run.triggered.connect(self.parent.adb.run) self.action_RunFile = QAction(Icons.go, 'Cmd', self) self.action_RunFile.triggered.connect(self.parent.openCommand) self.parent.runButton.clicked.connect(self.parent.command.setCmdLine) self.action_Stop = QAction(Icons.stop, 'Stop', self) self.action_Stop.setShortcut('Ctrl+Q') self.action_Stop.triggered.connect(self.parent.adb.stop) self.action_Design = QAction(Icons.color_palette, 'Design', self) self.action_Design.triggered.connect(self.parent.design) self.action_Level = QAction(Icons.cmpC_pal, 'Level', self) self.action_Level.triggered.connect(self.parent.level) self.action_Todo = QAction(Icons.task_set, 'Todo', self) self.action_Todo.triggered.connect(self.parent.todo) self.action_Help = QAction(Icons.toc_open, 'Help', self) self.action_Help.triggered.connect(self.parent.help) self.action_Full = QAction(Icons.fullscreen, 'Full', self) self.action_Full.triggered.connect(self.parent.full) self.action_Stop.setDisabled(True) self.setToolLabel() self.setAllowedAreas(Qt.AllToolBarAreas) #self.setFixedHeight(40) #self.setIconSize(QSize(config.iconSize(),config.iconSize())) ''' Adding all Actions ''' self.addAction(self.action_NewProject) self.addAction(self.action_Open) self.addAction(self.action_Save) self.addAction(self.action_SaveAll) #self.addAction(self.action_Refresh) self.addSeparator() self.addAction(self.action_Build) self.addAction(self.action_Run) #self.addAction(self.action_RunFile) self.addAction(self.action_Stop) self.addAction(self.action_Debug) self.addSeparator() self.addAction(self.action_Design) self.addAction(self.action_Level) self.addAction(self.action_Todo) self.initOptionsMenu() self.addSeparator() self.initStyleMenu() self.initLexerMenu() self.initApiMenu() #self.addAction(self.action_Help) #self.addAction(self.action_Full) self.addSeparator() self.initModeMenu() def colorChange(self, text, color): #print "colorChange ",text,color editStyle = config.readStyle() editStyle[text] = color config.writeStyle(editStyle) for i in range(len(self.parent.files)): self.parent.tabWidget.widget(i).setEditorStyle() def setColors(self,action): print action.text() def changeAll(self): self.colorChange("base", "#ffffff") def setIcon(self,val): config.setIconSize(val) self.setIconSize(QSize(val,val)) def setToolLabel(self): if (config.toolLabel()): self.setToolButtonStyle(Qt.ToolButtonIconOnly) self.setIconSize(QSize(24,24)) else: self.setIconSize(QSize(16,16)) self.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) '''Important for multiple callbacks in for loop''' def make_callback(self, text): return lambda:self.colorChange(text) ''' Options Menu ''' def initOptionsMenu(self): men = QMenu() #Threshold Slider self.threshSlider = QSlider() self.threshSlider.setTickPosition(QSlider.TicksLeft) self.threshSlider.setOrientation(Qt.Horizontal) self.threshSlider.setValue(config.thresh()) self.threshSlider.setMinimum(0) self.threshSlider.setMaximum(5) self.threshSlider.valueChanged.connect(self.parent.setThreshold) self.threshSliderAction = QWidgetAction(men) self.threshSliderAction.setDefaultWidget(self.threshSlider) #TabsWidth Slider self.tabsSlider = QSlider() self.tabsSlider.setTickPosition(QSlider.TicksLeft) self.tabsSlider.setOrientation(Qt.Horizontal) self.tabsSlider.setValue(config.tabwidth()) self.tabsSlider.setMinimum(0) self.tabsSlider.setMaximum(8) self.tabsSlider.valueChanged.connect(self.parent.setTabWidth) self.tabsSliderAction = QWidgetAction(men) self.tabsSliderAction.setDefaultWidget(self.tabsSlider) #iconSize Slider self.iconSlider = QSlider() self.iconSlider.setTickPosition(QSlider.TicksLeft) self.iconSlider.setOrientation(Qt.Horizontal) self.iconSlider.setValue(config.iconSize()) self.iconSlider.setMinimum(16) self.iconSlider.setMaximum(32) self.iconSlider.setSingleStep(2) self.iconSlider.valueChanged.connect(self.setIcon) self.iconSliderAction = QWidgetAction(men) self.iconSliderAction.setDefaultWidget(self.iconSlider) '''Font Button''' self.fontCombo = QFontComboBox() self.fontCombo.currentFontChanged.connect(self.parent.setFont) self.fontCombo.setCurrentFont(QFont(config.fontName())) self.fontComboMenu = QWidgetAction(men) self.fontComboMenu.setDefaultWidget(self.fontCombo) '''Font Size''' self.fontSizeCombo = QComboBox() for size in range(1,40): self.fontSizeCombo.addItem(str(size)) self.fontSizeCombo.setCurrentIndex(config.fontSize()) self.fontSizeCombo.currentIndexChanged.connect(self.parent.setFontSize) self.fontSizeComboMenu = QWidgetAction(men) self.fontSizeComboMenu.setDefaultWidget(self.fontSizeCombo) action_Android = QAction(Icons.android,'Android', self) action_Android.triggered.connect(self.parent.android) action_Ant = QAction(Icons.ant_view,'Ant', self) action_Ant.triggered.connect(self.parent.antt) action_Squirrel = QAction(Icons.nut,'Squirrel', self) action_Squirrel.triggered.connect(self.parent.squirrel) action_Ios1 = QAction(Icons.ios,'iOS', self) action_Update = QAction(Icons.update,"Update",self) action_Update.triggered.connect(self.parent.update) action_explorer = QAction("Explorer",self) action_explorer.triggered.connect(self.parent.exp) action_explorer.setCheckable(True) action_explorer.setChecked(True) action_console = QAction("Console",self) action_console.triggered.connect(self.parent.cmd) action_console.setCheckable(True) action_console.setChecked(False) #action_designer = QAction("Designer",self) #action_designer.triggered.connect(self.parent.design) action_Indentation = QAction("Indentation Guides",self) action_Indentation.triggered.connect(self.parent.setIndent) action_Indentation.setCheckable(True) action_Indentation.setChecked(config.indent()) action_WhiteSpace = QAction("WhiteSpace",self) action_WhiteSpace.triggered.connect(self.parent.setWhiteSpace) action_WhiteSpace.setCheckable(True) action_WhiteSpace.setChecked(config.whiteSpace()) action_EndLine = QAction("End of Lines",self) action_EndLine.triggered.connect(self.parent.setEndLine) action_EndLine.setCheckable(True) action_Margin = QAction("Line Numbers",self) action_Margin.triggered.connect(self.parent.setMargin) action_Margin.setCheckable(True) action_Margin.setChecked(config.margin()) action_ToolLabel = QAction("Tool Labels",self) action_ToolLabel.triggered.connect(self.setToolLabel) action_ToolLabel.setCheckable(True) #action_ToolLabel.setChecked(config.toolLabel()) '''Encoding''' encodingGroup = QActionGroup(self) encodingGroup.setExclusive(True) action_Ascii = QAction("Ascii",encodingGroup) action_Ascii.setCheckable(True) action_Unicode = QAction("Unicode",encodingGroup) action_Unicode.setCheckable(False) encodingGroup.addAction(action_Ascii) encodingGroup.addAction(action_Unicode) encodingGroup.selected.connect(self.parent.setEncoding) if(config.encoding() == Encoding.ASCII): action_Ascii.setChecked(True) else: action_Unicode.setChecked(True) men.addAction(action_Update) men.addAction(self.action_Help) men.addAction(self.action_Full) men.addSeparator() men.addAction(action_Android) men.addAction(action_Ant) men.addAction(action_Squirrel) men.addAction(action_Ios1) men.addSeparator() men.addAction(action_explorer) men.addAction(action_console) #men.addAction(action_designer) men.addSeparator() men.addAction(action_Indentation) men.addAction(action_WhiteSpace) men.addAction(action_EndLine) men.addAction(action_Margin) men.addAction(action_ToolLabel) men.addSeparator() men.addActions(encodingGroup.actions()) men.addSeparator() head_font = QLabel("Font---------------------") fnt = head_font.font() fnt.setBold(True) head_font.setFont(fnt) head_fontWidgetAction = QWidgetAction(men) head_fontWidgetAction.setDefaultWidget(head_font) men.addAction(head_fontWidgetAction) men.addAction(self.fontComboMenu) men.addAction(self.fontSizeComboMenu) men.addSeparator() men.addAction(QAction("TabWidth",self)) men.addAction(self.tabsSliderAction) men.addSeparator() men.addAction(QAction("Threshold",self)) men.addAction(self.threshSliderAction) #men.addAction(QAction("Icon Size",self)) #men.addAction(self.iconSliderAction) self.action_Options = QAction(Icons.emblem_system, 'Options', self) self.action_Options.setMenu(men) self.addAction(self.action_Options) ''' Mode Menu ''' def initModeMenu(self): self.modeGroup = QActionGroup(self) self.modeGroup.setExclusive(True) self.modeGroup.selected.connect(self.parent.setMode) self.action_Squirrel = QAction(Icons.nut, 'Squ', self.modeGroup) self.action_Squirrel.setCheckable(True) self.action_Emo = QAction(Icons.emo, 'Emo', self.modeGroup) self.action_Emo.setCheckable(True) self.action_And = QAction(Icons.android, 'Android', self.modeGroup) self.action_And.setCheckable(True) self.action_Ios = QAction(Icons.ios, 'ios', self.modeGroup) self.action_Ios.setCheckable(True) self.modeGroup.addAction(self.action_Squirrel) self.modeGroup.addAction(self.action_Emo) self.modeGroup.addAction(self.action_And) self.modeGroup.addAction(self.action_Ios) self.addActions(self.modeGroup.actions()) if(config.mode() == 0): self.action_Squirrel.setChecked(True) self.action_Build.setEnabled(False) self.action_Run.setEnabled(False) elif(config.mode() == 1): self.action_Emo.setChecked(True) self.action_Build.setEnabled(True) self.action_Run.setEnabled(True) elif(config.mode() == 2): self.action_And.setChecked(True) self.action_Build.setEnabled(True) self.action_Run.setEnabled(True) elif(config.mode() == 3): self.action_Ios.setChecked(True) self.action_Build.setEnabled(False) self.action_Run.setEnabled(False) ''' Style Menu ''' def initStyleMenu(self): editStyle = config.readStyle() self.action_Style = QAction(Icons.style, 'Style', self) men = QMenu(self) men1 = QMenu() self.base = StyleWidget(self,"base",editStyle["base"]) self.back = StyleWidget(self,"back",editStyle["back"]) self.caret = StyleWidget(self,"caret",editStyle["caret"]) self.margin = StyleWidget(self,"margin",editStyle["margin"]) self.marker = StyleWidget(self,"marker",editStyle["marker"]) self.comment = StyleWidget(self,"comment",editStyle["comment"]) self.number = StyleWidget(self,"number",editStyle["number"]) self.keyword = StyleWidget(self,"keyword",editStyle["keyword"]) self.string = StyleWidget(self,"string",editStyle["string"]) self.operator = StyleWidget(self,"operator",editStyle["operator"]) self.connect(self.base, SIGNAL("colorChange"),self.colorChange) self.connect(self.back, SIGNAL("colorChange"),self.colorChange) self.connect(self.caret, SIGNAL("colorChange"),self.colorChange) self.connect(self.margin, SIGNAL("colorChange"),self.colorChange) self.connect(self.marker, SIGNAL("colorChange"),self.colorChange) self.connect(self.comment, SIGNAL("colorChange"),self.colorChange) self.connect(self.number, SIGNAL("colorChange"),self.colorChange) self.connect(self.keyword, SIGNAL("colorChange"),self.colorChange) self.connect(self.string, SIGNAL("colorChange"),self.colorChange) self.connect(self.operator, SIGNAL("colorChange"),self.colorChange) self.baseMenu = QWidgetAction(men) self.baseMenu.setDefaultWidget(self.base) self.backMenu = QWidgetAction(men) self.backMenu.setDefaultWidget(self.back) self.caretMenu = QWidgetAction(men) self.caretMenu.setDefaultWidget(self.caret) self.marginMenu = QWidgetAction(men) self.marginMenu.setDefaultWidget(self.margin) self.markerMenu = QWidgetAction(men) self.markerMenu.setDefaultWidget(self.marker) self.commentMenu = QWidgetAction(men) self.commentMenu.setDefaultWidget(self.comment) self.numberMenu = QWidgetAction(men) self.numberMenu.setDefaultWidget(self.number) self.keywordMenu = QWidgetAction(men) self.keywordMenu.setDefaultWidget(self.keyword) self.stringMenu = QWidgetAction(men) self.stringMenu.setDefaultWidget(self.string) self.operatorMenu = QWidgetAction(men) self.operatorMenu.setDefaultWidget(self.operator) self.styleGroup = QActionGroup(self) self.styleGroup.setExclusive(True) self.styleGroup.selected.connect(self.setColors) self.style1 = QAction("All Hallow's Eve",self.styleGroup) self.style1.setCheckable(True) self.style2 = QAction("Amy",self.styleGroup) self.style2.setCheckable(True) self.style3 = QAction("Aptana Studio",self.styleGroup) self.style3.setCheckable(True) self.style4 = QAction("Bespin",self.styleGroup) self.style4.setCheckable(True) self.style5 = QAction("Blackboard",self.styleGroup) self.style5.setCheckable(True) self.style6 = QAction("Choco",self.styleGroup) self.style6.setCheckable(True) self.style7 = QAction("Cobalt",self.styleGroup) self.style7.setCheckable(True) self.style8 = QAction("Dawn",self.styleGroup) self.style8.setCheckable(True) self.style9 = QAction("Eclipse",self.styleGroup) self.style9.setCheckable(True) self.styleGroup.addAction(self.style1) self.styleGroup.addAction(self.style2) self.styleGroup.addAction(self.style3) self.styleGroup.addAction(self.style4) self.styleGroup.addAction(self.style5) self.styleGroup.addAction(self.style6) self.styleGroup.addAction(self.style7) self.styleGroup.addAction(self.style8) self.styleGroup.addAction(self.style9) men1.addAction(self.baseMenu) men1.addAction(self.backMenu) men1.addAction(self.caretMenu) men1.addAction(self.marginMenu) men1.addAction(self.markerMenu) men1.addAction(self.commentMenu) men1.addAction(self.numberMenu) men1.addAction(self.keywordMenu) men1.addAction(self.stringMenu) men1.addAction(self.operatorMenu) men1.addSeparator() men2 = QMenu(self) men2.setTitle("Styles") men2.addActions(self.styleGroup.actions()) men1.addMenu(men2) self.action_Style.setMenu(men1) self.addAction(self.action_Style) ''' Lexer Menu''' def make_action_lex(self, text): action = QAction(text, self.lexGroup) action.setCheckable(True) return action def initLexerMenu(self): self.action_Lexer = QAction(Icons.file_obj, 'Lexer', self) men = QMenu() self.lexGroup = QActionGroup(self) self.lexGroup.setExclusive(True) self.lexGroup.selected.connect(self.parent.setLexer) #langs = [i for i in dir(Qsci) if i.startswith('QsciLexer')] langs = ['Bash', 'Batch', 'CMake', 'CPP', 'CSS', 'C#','HTML','Java', 'JavaScript', 'Lua', 'Makefile','Python', 'SQL', 'XML', 'YAML'] for l in langs: act = self.make_action_lex(l) self.lexGroup.addAction(act) if(langs.index(l) == 8): #For javascript act.setChecked(True) #print l[9:] # we don't need to print "QsciLexer" before each name men.addActions(self.lexGroup.actions()) self.action_Lexer.setMenu(men) self.addAction(self.action_Lexer) ''' Api Menu ''' def make_action_api(self, text): action = QAction(text, self.apiGroup) action.setCheckable(True) return action def initApiMenu(self): self.action_Api = QAction(Icons.lib, 'Api', self) men = QMenu() self.apiGroup = QActionGroup(self) self.apiGroup.setExclusive(True) self.apiGroup.selected.connect(self.parent.setApi) list = oslistdir(apiDir) apis = [] if(list != None): for i in list: if i.endswith("api"): apis.append(i.replace(".api", "")) if(apis != None): for i in apis: act = self.make_action_api(i) self.apiGroup.addAction(act) if(i == "emo"): #For emo act.setChecked(True) men.addActions(self.apiGroup.actions()) self.action_Api.setMenu(men) self.addAction(self.action_Api)
class Trackers(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.v_layout = QVBoxLayout() self.hSliderMin = QSlider() self.hSliderMin.setOrientation(Qt.Horizontal) self.hLabelMin = QLabel('H min: 0') self.hSliderMin.setMinimum(0) self.hSliderMin.setMaximum(179) self.hSliderMax = QSlider() self.hSliderMax.setOrientation(Qt.Horizontal) self.hLabelMax = QLabel('H max: 0') self.hSliderMax.setMinimum(0) self.hSliderMax.setMaximum(179) self.sSliderMin = QSlider() self.sSliderMin.setOrientation(Qt.Horizontal) self.sLabelMin = QLabel('S min: 0') self.sSliderMin.setMinimum(0) self.sSliderMin.setMaximum(255) self.sSliderMax = QSlider() self.sSliderMax.setOrientation(Qt.Horizontal) self.sLabelMax = QLabel('S max: 0') self.sSliderMax.setMinimum(0) self.sSliderMax.setMaximum(255) self.vSliderMin = QSlider() self.vSliderMin.setOrientation(Qt.Horizontal) self.vLabelMin = QLabel('V min: 0') self.vSliderMin.setMinimum(0) self.vSliderMin.setMaximum(255) self.vSliderMax = QSlider() self.vSliderMax.setOrientation(Qt.Horizontal) self.vLabelMax = QLabel('V max: 0') self.vSliderMax.setMinimum(0) self.vSliderMax.setMaximum(255) self.v_layout.addWidget(self.hLabelMin) self.v_layout.addWidget(self.hSliderMin) self.v_layout.addWidget(self.hLabelMax) self.v_layout.addWidget(self.hSliderMax) self.v_layout.addWidget(self.sLabelMin) self.v_layout.addWidget(self.sSliderMin) self.v_layout.addWidget(self.sLabelMax) self.v_layout.addWidget(self.sSliderMax) self.v_layout.addWidget(self.vLabelMin) self.v_layout.addWidget(self.vSliderMin) self.v_layout.addWidget(self.vLabelMax) self.v_layout.addWidget(self.vSliderMax) self.setLayout(self.v_layout) self.hSliderMin.valueChanged.connect(self.slider_movedHmin) self.sSliderMin.valueChanged.connect(self.slider_movedSmin) self.vSliderMin.valueChanged.connect(self.slider_movedVmin) self.hSliderMax.valueChanged.connect(self.slider_movedHmax) self.sSliderMax.valueChanged.connect(self.slider_movedSmax) self.vSliderMax.valueChanged.connect(self.slider_movedVmax) def keyPressEvent(self, event): if event.key()==Qt.Key_Right: self.slider.setValue(self.slider.value() + 1) elif event.key()==Qt.Key_Left: self.slider.setValue(self.slider.value() - 1) else: QWidget.keyPressEvent(self, event) def slider_movedHmin(self, position): self.hLabelMin.setText('H min: %d' % position) def slider_movedSmin(self, position): self.sLabelMin.setText('S min: %d' % position) def slider_movedVmin(self, position): self.vLabelMin.setText('V min: %d' % position) def slider_movedHmax(self, position): self.hLabelMax.setText('H max: %d' % position) def slider_movedSmax(self, position): self.sLabelMax.setText('S max: %d' % position) def slider_movedVmax(self, position): self.vLabelMax.setText('V max: %d' % position)
class SliderDlg(QDialog): def __init__(self, parent, sigma): QDialog.__init__(self, parent, Qt.FramelessWindowHint) # init # ------------------------------------------------ self.oldSigma = sigma self.sigma = sigma self.brushSize = 0 self.setStyleSheet("background-color:window;") # widgets and layouts # ------------------------------------------------ self.layout = QVBoxLayout() self.setLayout(self.layout) labelsLayout = QHBoxLayout() self.labelSigma = QLabel("Sigma: xx") self.labelBrushSize = QLabel("BrushSize: xx") labelsLayout.addWidget(self.labelSigma) labelsLayout.addWidget(self.labelBrushSize) self.layout.addLayout(labelsLayout) self.slider = QSlider(Qt.Horizontal) self.slider.setMinimum(1) self.slider.setMaximum(100) self.slider.sliderMoved.connect(self.on_sliderMoved) self.layout.addWidget(self.slider) self.buttonsLayout = QHBoxLayout() self.cancel = QToolButton() self.cancel.setText("cancel") self.cancel.clicked.connect(self.on_cancelClicked) self.buttonsLayout.addWidget(self.cancel) self.ok = QToolButton() self.ok.setText("OK") self.ok.clicked.connect(self.on_okClicked) self.buttonsLayout.addWidget(self.ok) self.layout.addLayout(self.buttonsLayout) self.layout.setContentsMargins(10, 0, 10, 0) labelsLayout.setContentsMargins(0, 0, 0, 0) self.buttonsLayout.setContentsMargins(0, 0, 0, 0) self.setlabelSigma() self.setLabelBrushSize() self.setSliderPosition() def setlabelSigma(self): self.labelSigma.setText("Sigma: " + str(self.sigma)) def setLabelBrushSize(self): self.brushSize = int(3.0*self.sigma + 0.5)*2 + 1 self.labelBrushSize.setText("BrushSize: " + str(self.brushSize)) def setSliderPosition(self): self.slider.setSliderPosition(self.sigma*10) def on_sliderMoved(self, i): self.sigma = float(i)/10 self.setlabelSigma() self.setLabelBrushSize() self.parent().parent().parent().preView.setSizeToLabel(self.brushSize) def on_cancelClicked(self): self.reject() def on_okClicked(self): self.accept() def exec_(self): if QDialog.exec_(self) == QDialog.Accepted: return self.sigma else: return self.oldSigma
class FeeSelectionDialog(ArmoryDialog): ############################################################################# def __init__(self, parent, main, cs_callback, get_csstate): super(FeeSelectionDialog, self).__init__(parent, main) #Button Label self.lblButtonFee = QLabelButton("") #get default values flatFee = self.main.getSettingOrSetDefault("Default_Fee", MIN_TX_FEE) flatFee = coin2str(flatFee, maxZeros=1).strip() fee_byte = str(self.main.getSettingOrSetDefault("Default_FeeByte", MIN_FEE_BYTE)) blocksToConfirm = self.main.getSettingOrSetDefault(\ "Default_FeeByte_BlocksToConfirm", NBLOCKS_TO_CONFIRM) self.coinSelectionCallback = cs_callback self.getCoinSelectionState = get_csstate self.validAutoFee = True try: autoFee_byte = str(estimateFee(blocksToConfirm) / 1000.0) except: autoFee_byte = "N/A" self.validAutoFee = False defaultCheckState = \ self.main.getSettingOrSetDefault("FeeOption", DEFAULT_FEE_TYPE) #flat free def setFlatFee(): def callbck(): return self.selectType('FlatFee') return callbck def updateLbl(): self.updateCoinSelection() self.radioFlatFee = QRadioButton(self.tr("Flat Fee (BTC)")) self.edtFeeAmt = QLineEdit(flatFee) self.edtFeeAmt.setFont(GETFONT('Fixed')) self.edtFeeAmt.setMinimumWidth(tightSizeNChar(self.edtFeeAmt, 6)[0]) self.edtFeeAmt.setMaximumWidth(tightSizeNChar(self.edtFeeAmt, 12)[0]) self.connect(self.radioFlatFee, SIGNAL('clicked()'), setFlatFee()) self.connect(self.edtFeeAmt, SIGNAL('textChanged(QString)'), updateLbl) frmFlatFee = QFrame() frmFlatFee.setFrameStyle(STYLE_RAISED) layoutFlatFee = QGridLayout() layoutFlatFee.addWidget(self.radioFlatFee, 0, 0, 1, 1) layoutFlatFee.addWidget(self.edtFeeAmt, 0, 1, 1, 1) frmFlatFee.setLayout(layoutFlatFee) #fee/byte def setFeeByte(): def callbck(): return self.selectType('FeeByte') return callbck self.radioFeeByte = QRadioButton(self.tr("Fee/Byte (Satoshi/Byte)")) self.edtFeeByte = QLineEdit(fee_byte) self.edtFeeByte.setFont(GETFONT('Fixed')) self.edtFeeByte.setMinimumWidth(tightSizeNChar(self.edtFeeByte, 6)[0]) self.edtFeeByte.setMaximumWidth(tightSizeNChar(self.edtFeeByte, 12)[0]) self.connect(self.radioFeeByte, SIGNAL('clicked()'), setFeeByte()) self.connect(self.edtFeeByte, SIGNAL('textChanged(QString)'), updateLbl) frmFeeByte = QFrame() frmFeeByte.setFrameStyle(STYLE_RAISED) layoutFeeByte = QGridLayout() layoutFeeByte.addWidget(self.radioFeeByte, 0, 0, 1, 1) layoutFeeByte.addWidget(self.edtFeeByte, 0, 1, 1, 1) frmFeeByte.setLayout(layoutFeeByte) #auto fee/byte def setAutoFeeByte(): def callbck(): return self.selectType('Auto') return callbck radioButtonTxt = self.tr("Fee rate from node (sat/Byte): ") if not self.validAutoFee: radioButtonTxt = self.tr("Failed to fetch fee/byte from node") self.radioAutoFeeByte = QRadioButton(radioButtonTxt) self.lblAutoFeeByte = QLabel(autoFee_byte) self.lblAutoFeeByte.setFont(GETFONT('Fixed')) self.lblAutoFeeByte.setMinimumWidth(tightSizeNChar(self.lblAutoFeeByte, 6)[0]) self.lblAutoFeeByte.setMaximumWidth(tightSizeNChar(self.lblAutoFeeByte, 12)[0]) self.sliderAutoFeeByte = QSlider(Qt.Horizontal, self) self.sliderAutoFeeByte.setMinimum(2) self.sliderAutoFeeByte.setMaximum(6) self.sliderAutoFeeByte.setValue(blocksToConfirm) self.lblSlider = QLabel() def getSliderLabelTxt(): return self.tr("Blocks to confirm: %1").arg(\ unicode(self.sliderAutoFeeByte.value())) def updateAutoFeeByte(): blocksToConfirm = self.sliderAutoFeeByte.value() try: autoFee_byte = str(estimateFee(blocksToConfirm) / 1000.0) except: autoFee_byte = "N/A" self.lblSlider.setText(getSliderLabelTxt()) self.lblAutoFeeByte.setText(autoFee_byte) updateLbl() self.lblSlider.setText(getSliderLabelTxt()) self.connect(self.radioAutoFeeByte, SIGNAL('clicked()'), setAutoFeeByte()) self.sliderAutoFeeByte.valueChanged.connect(updateAutoFeeByte) self.sliderAutoFeeByte.setEnabled(False) frmAutoFeeByte = QFrame() frmAutoFeeByte.setFrameStyle(STYLE_RAISED) layoutAutoFeeByte = QGridLayout() layoutAutoFeeByte.addWidget(self.radioAutoFeeByte, 0, 0, 1, 1) layoutAutoFeeByte.addWidget(self.lblAutoFeeByte, 0, 1, 1, 1) layoutAutoFeeByte.addWidget(self.lblSlider, 1, 0, 1, 2) layoutAutoFeeByte.addWidget(self.sliderAutoFeeByte, 2, 0, 1, 2) frmAutoFeeByte.setLayout(layoutAutoFeeByte) if not self.validAutoFee: frmAutoFeeByte.setEnabled(False) #adjust and close self.btnClose = QPushButton(self.tr('Close')) self.connect(self.btnClose, SIGNAL('clicked()'), self.accept) self.checkBoxAdjust = QCheckBox(self.tr('Adjust fee/byte for privacy')) self.checkBoxAdjust.setChecked(\ self.main.getSettingOrSetDefault('AdjustFee', True)) self.connect(self.checkBoxAdjust, SIGNAL('clicked()'), updateLbl) frmClose = makeHorizFrame(\ [self.checkBoxAdjust, 'Stretch', self.btnClose], STYLE_NONE) #main layout layout = QGridLayout() layout.addWidget(frmAutoFeeByte, 0, 0, 1, 4) layout.addWidget(frmFeeByte, 2, 0, 1, 4) layout.addWidget(frmFlatFee, 4, 0, 1, 4) layout.addWidget(frmClose, 5, 0, 1, 4) self.setLayout(layout) self.setWindowTitle(self.tr('Select Fee Type')) self.selectType(defaultCheckState) self.setFocus() ############################################################################# def selectType(self, strType): self.radioFlatFee.setChecked(False) self.radioFeeByte.setChecked(False) self.radioAutoFeeByte.setChecked(False) self.sliderAutoFeeByte.setEnabled(False) if strType == 'FlatFee': self.radioFlatFee.setChecked(True) elif strType == 'FeeByte': self.radioFeeByte.setChecked(True) elif strType == 'Auto': if not self.validAutoFee: self.radioFeeByte.setChecked(True) else: self.radioAutoFeeByte.setChecked(True) self.sliderAutoFeeByte.setEnabled(True) self.updateCoinSelection() self.updateLabelButton() ############################################################################# def updateCoinSelection(self): try: self.coinSelectionCallback() except: self.updateLabelButton() ############################################################################# def getLabelButton(self): return self.lblButtonFee ############################################################################# def updateLabelButtonText(self, txSize, flatFee, fee_byte): txSize = str(txSize) if txSize != 'N/A': txSize += " B" if flatFee != 'N/A': flatFee = coin2str(flatFee, maxZeros=0).strip() flatFee += " BTC" if not isinstance(fee_byte, str): fee_byte = '%.2f' % fee_byte lblStr = "Size: %s, Fee: %s" % (txSize, flatFee) if fee_byte != 'N/A': lblStr += " (%s sat/B)" % fee_byte self.lblButtonFee.setText(lblStr) ############################################################################# def updateLabelButton(self, reset=False): try: if reset: raise Exception() txSize, flatFee, feeByte = self.getCoinSelectionState() self.updateLabelButtonText(txSize, flatFee, feeByte) except: self.updateLabelButtonText('N/A', 'N/A', 'N/A') ############################################################################# def resetLabel(self): self.updateLabelButton(True) ############################################################################# def getFeeData(self): fee = 0 fee_byte = 0 if self.radioFlatFee.isChecked(): flatFeeText = str(self.edtFeeAmt.text()) fee = str2coin(flatFeeText) elif self.radioFeeByte.isChecked(): fee_byteText = str(self.edtFeeByte.text()) fee_byte = float(fee_byteText) elif self.radioAutoFeeByte.isChecked(): fee_byteText = str(self.lblAutoFeeByte.text()) fee_byte = float(fee_byteText) adjust_fee = self.checkBoxAdjust.isChecked() return fee, fee_byte, adjust_fee
class options(QWidget): def __init__(self, parent): QWidget.__init__(self) self.init(parent) self.initShape() def init(self, parent): self.heditor = parent def initShape(self): self.vbox = QVBoxLayout() self.optab = QTabWidget() self.fill = QWidget() self.createHexOptions() # self.createPageOptions() self.createPixelOptions() self.vbox.addWidget(self.optab) self.createButtons() self.vbox.addWidget(self.fill) self.setLayout(self.vbox) def createPageOptions(self): self.pagegrid = QGridLayout() self.pagegroup = QWidget() pagelabel = QLabel("Page size : ") self.sizeEdit = QFFSpinBox(self) self.sizeEdit.setMaximum(self.heditor.filesize) self.sizeEdit.setValue(self.heditor.pageSize) # psize = QString("%.2d" % self.heditor.pageSize) # self.sizeEdit.insert(psize) headerlabel = QLabel("Header size : ") self.headEdit = QFFSpinBox(self) self.headEdit.setMaximum(self.heditor.filesize) self.headEdit.setValue(self.heditor.pageHead) # phead = QString("%.2d" % self.heditor.pageHead) # self.headEdit.insert(phead) sparelabel = QLabel("Spare size : ") self.spareEdit = QFFSpinBox(self) self.spareEdit.setMaximum(self.heditor.filesize) self.spareEdit.setValue(self.heditor.pageSpare) # pspare = QString("%.2d" % self.heditor.pageSpare) # self.spareEdit.insert(pspare) ppb = QLabel("Pages per block:") self.pagesperblock = QComboBox() self.pagesperblock.addItem("8") self.pagesperblock.addItem("16") self.pagesperblock.addItem("32") self.pagesperblock.addItem("64") self.pagesperblock.addItem("128") self.pagesperblock.addItem("256") self.pagesperblock.addItem("512") self.pagesperblock.setCurrentIndex(2) lview = QLabel("Left indication: ") self.indic = QComboBox() self.indic.addItem("Offset") self.indic.addItem("Block") # self.pagesperlineEdit = QLineEdit() # ppl = QString("%.2d" % self.heditor.pagesPerBlock) # self.pagesperlineEdit.insert(ppl) self.pagegrid.addWidget(pagelabel, 0, 0) self.pagegrid.addWidget(self.sizeEdit, 0, 1) self.pagegrid.addWidget(headerlabel, 1, 0) self.pagegrid.addWidget(self.headEdit, 1, 1) self.pagegrid.addWidget(sparelabel, 2, 0) self.pagegrid.addWidget(self.spareEdit, 2, 1) self.pagegrid.addWidget(ppb, 3, 0) self.pagegrid.addWidget(self.pagesperblock, 3, 1) self.pagegrid.addWidget(lview, 4, 0) self.pagegrid.addWidget(self.indic, 4, 1) self.pagegrid.addWidget(self.fill, 5, 0) self.pagegrid.setRowStretch(5, 1) # self.pagegrid.addWidget(self.fill, 6, 0) # self.pagegrid.addWidget(pagesperline, 6, 0) # self.pagegrid.addWidget(self.pagesperlineEdit, 7, 0) self.pagegroup.setLayout(self.pagegrid) self.vvbox.addWidget(self.pagegroup) # self.optab.insertTab(1, self.pagegroup, "Pages" ) # self.vbox.addWidget(self.pagegroup) def createHexOptions(self): self.vvbox = QVBoxLayout() self.vcontainer = QWidget() self.hexgroup = QWidget() self.hexgrid = QGridLayout() groupebylabel = QLabel("Groupe by:") self.groupeby = QComboBox() self.groupeby.addItem("1") self.groupeby.addItem("2") self.groupeby.addItem("4") offsetlabel = QLabel("Offset as") self.offsetas = QComboBox() self.offsetas.addItem("Hexadecimal") self.offsetas.addItem("Decimal") # self.hexgrid.addWidget(groupebylabel, 0, 0) # self.hexgrid.addWidget(self.groupeby, 1, 0) self.hexgrid.addWidget(offsetlabel, 0, 0) self.hexgrid.addWidget(self.offsetas, 0, 1) # self.hexgrid.addWidget(self.fill, 2, 0) # self.hexgrid.setRowStretch(2, 1) self.hexgroup.setLayout(self.hexgrid) self.vvbox.addWidget(self.hexgroup) self.createPageOptions() self.vcontainer.setLayout(self.vvbox) self.optab.insertTab(0, self.vcontainer, "General") # self.vbox.addWidget(self.hexgroup) #Offset as decimal / hexadecimal def createPixelOptions(self): self.pixgroup = QWidget() self.pixgrid = QGridLayout() formatlabel = QLabel("Format :") self.format = QComboBox() self.format.addItem("RGB") self.format.addItem("Alpha RGB") self.format.addItem("Indexed 8bit") self.format.addItem("Mono") self.connect(self.format, SIGNAL("currentIndexChanged(const QString)"), self.formatChanged) colorlabel = QLabel("Indexed Color :") self.icolor = QComboBox() self.icolor.addItem("Green") self.icolor.addItem("Red") self.icolor.addItem("Blue") self.icolor.addItem("Ascii") self.icolor.addItem("256") self.icolor.setEnabled(False) slidelabel = QLabel("Resolution : ") self.sliderspin = QSpinBox(self) self.sliderspin.setMinimum(64) self.sliderspin.setMaximum(1024) self.sliderspin.setValue(self.heditor.wpixel.view.w) self.connect(self.sliderspin, SIGNAL("valueChanged(int)"), self.slidermoved) self.slider = QSlider(Qt.Horizontal) self.slider.setMinimum(64) self.slider.setMaximum(1024) self.slider.setValue(self.heditor.wpixel.view.w) self.slider.setSingleStep(1) self.zoomlabel = QLabel("Scale factor : 1") self.zoom = QSlider(Qt.Horizontal) self.zoom.setMinimum(1) self.zoom.setMaximum(5) self.zoom.setValue(1) self.zoom.setSingleStep(1) self.zoom.setTickInterval(1) self.zoom.setTickPosition(QSlider.TicksBelow) self.connect(self.slider, SIGNAL("sliderMoved(int)"), self.slidermoved) self.connect(self.zoom, SIGNAL("sliderMoved(int)"), self.scale) self.pixgrid.addWidget(formatlabel, 0, 0) self.pixgrid.addWidget(self.format, 0, 1) self.pixgrid.addWidget(colorlabel, 1, 0) self.pixgrid.addWidget(self.icolor, 1, 1) self.pixgrid.addWidget(slidelabel, 2, 0) self.pixgrid.addWidget(self.sliderspin, 2, 1, Qt.AlignLeft) self.pixgrid.addWidget(self.slider, 3, 0) self.pixgrid.addWidget(self.zoomlabel, 4, 0, Qt.AlignLeft) self.pixgrid.addWidget(self.zoom, 5, 0) self.pixgrid.addWidget(self.fill, 6, 0) self.pixgrid.setRowStretch(6, 1) self.pixgroup.setLayout(self.pixgrid) self.optab.insertTab(1, self.pixgroup, "Pixel") def setSliderLabel(self, value): cvalue = QString() cvalue = "%2.d" % value self.sliderlabel.setText(cvalue) def setZoomLabel(self, value): zvalue = QString("Scale factor : ") zvalue += "%2.d" % value self.zoomlabel.setText(zvalue) def createButtons(self): self.applyB = QPushButton("Apply") self.connect(self.applyB, SIGNAL('clicked()'), self.apply) self.vbox.addWidget(self.applyB) def checkValue(self, value): try: n = int(value) return n except ValueError: return -1 def apply(self): #PAGE CHECK pagesize = self.sizeEdit.value() headsize = self.headEdit.value() sparesize = self.spareEdit.value() pagesperblock = self.checkValue(self.pagesperblock.currentText()) if (pagesize < 0) or (headsize < 0) or (sparesize < 0) or (pagesperblock < 0): print "Wrong values" else: offas = self.offsetas.currentText() if offas == "Decimal": self.heditor.decimalview = True elif offas == "Hexadecimal": self.heditor.decimalview = False #Hexview refresh self.heditor.readOffset(self.heditor.currentOffset) #Pageview refresh if self.indic.currentText() == "Offset": self.heditor.pageOffView = True else: self.heditor.pageOffView = False self.heditor.refreshPageValues(headsize, pagesize, sparesize, pagesperblock) if self.heditor.wpage.scroll: self.heditor.wpage.scroll.refreshValues( self.heditor.pagesPerBlock, self.heditor.pageSize) self.heditor.wpage.view.refreshAllContent() #PageView scrollbar refres #Pixel View refresh format = self.format.currentText() if format == "Indexed 8bit": self.heditor.wpixel.view.format = 0 elif format == "Mono": self.heditor.wpixel.view.format = 1 elif format == "RGB": self.heditor.wpixel.view.format = 2 elif format == "Alpha RGB": self.heditor.wpixel.view.format = 3 if self.heditor.wpixel.scroll: self.heditor.wpixel.scroll.refreshValues() #Color icolor = self.icolor.currentText() if icolor == "Red": self.heditor.wpixel.view.icolor = 0 elif icolor == "Green": self.heditor.wpixel.view.icolor = 1 elif icolor == "Blue": self.heditor.wpixel.view.icolor = 2 elif icolor == "Ascii": self.heditor.wpixel.view.icolor = 3 elif icolor == "256": self.heditor.wpixel.view.icolor = 4 pixoffset = self.heditor.wpixel.view.currentOffset self.heditor.wpixel.view.read_image(pixoffset) def slidermoved(self, value): pixoffset = self.heditor.wpixel.view.currentOffset self.heditor.wpixel.view.w = value self.sliderspin.setValue(value) # self.setSliderLabel(value) self.heditor.wpixel.view.read_image(pixoffset) if self.heditor.wpixel.scroll: self.heditor.wpixel.scroll.refreshValues() # print value def scale(self, value): self.setZoomLabel(value) self.heditor.wpixel.view.scale = value pixoffset = self.heditor.wpixel.view.currentOffset self.heditor.wpixel.view.read_image(pixoffset) def formatChanged(self, format): if format == "Indexed 8bit": self.icolor.setEnabled(True) else: self.icolor.setEnabled(False) def keyPressEvent(self, kEvent): key = kEvent.key() if key == Qt.Key_Return or key == Qt.Key_Enter: self.apply()
class options(QWidget): def __init__(self, parent): QWidget.__init__(self) self.init(parent) self.initShape() def init(self, parent): self.heditor = parent def initShape(self): self.vbox = QVBoxLayout() self.optab = QTabWidget() self.fill = QWidget() self.createHexOptions() # self.createPageOptions() self.createPixelOptions() self.vbox.addWidget(self.optab) self.createButtons() self.vbox.addWidget(self.fill) self.setLayout(self.vbox) def createPageOptions(self): self.pagegrid = QGridLayout() self.pagegroup = QWidget() pagelabel = QLabel("Page size : ") self.sizeEdit = QFFSpinBox(self) self.sizeEdit.setMaximum(self.heditor.filesize) self.sizeEdit.setValue(self.heditor.pageSize) # psize = QString("%.2d" % self.heditor.pageSize) # self.sizeEdit.insert(psize) headerlabel = QLabel("Header size : ") self.headEdit = QFFSpinBox(self) self.headEdit.setMaximum(self.heditor.filesize) self.headEdit.setValue(self.heditor.pageHead) # phead = QString("%.2d" % self.heditor.pageHead) # self.headEdit.insert(phead) sparelabel = QLabel("Spare size : ") self.spareEdit = QFFSpinBox(self) self.spareEdit.setMaximum(self.heditor.filesize) self.spareEdit.setValue(self.heditor.pageSpare) # pspare = QString("%.2d" % self.heditor.pageSpare) # self.spareEdit.insert(pspare) ppb = QLabel("Pages per block:") self.pagesperblock = QComboBox() self.pagesperblock.addItem("8") self.pagesperblock.addItem("16") self.pagesperblock.addItem("32") self.pagesperblock.addItem("64") self.pagesperblock.addItem("128") self.pagesperblock.addItem("256") self.pagesperblock.addItem("512") self.pagesperblock.setCurrentIndex(2) lview = QLabel("Left indication: ") self.indic = QComboBox() self.indic.addItem("Offset") self.indic.addItem("Block") # self.pagesperlineEdit = QLineEdit() # ppl = QString("%.2d" % self.heditor.pagesPerBlock) # self.pagesperlineEdit.insert(ppl) self.pagegrid.addWidget(pagelabel, 0, 0) self.pagegrid.addWidget(self.sizeEdit, 0, 1) self.pagegrid.addWidget(headerlabel, 1, 0) self.pagegrid.addWidget(self.headEdit, 1, 1) self.pagegrid.addWidget(sparelabel, 2, 0) self.pagegrid.addWidget(self.spareEdit, 2, 1) self.pagegrid.addWidget(ppb, 3 ,0) self.pagegrid.addWidget(self.pagesperblock, 3, 1) self.pagegrid.addWidget(lview, 4, 0) self.pagegrid.addWidget(self.indic, 4, 1) self.pagegrid.addWidget(self.fill, 5, 0) self.pagegrid.setRowStretch(5, 1) # self.pagegrid.addWidget(self.fill, 6, 0) # self.pagegrid.addWidget(pagesperline, 6, 0) # self.pagegrid.addWidget(self.pagesperlineEdit, 7, 0) self.pagegroup.setLayout(self.pagegrid) self.vvbox.addWidget(self.pagegroup) # self.optab.insertTab(1, self.pagegroup, "Pages" ) # self.vbox.addWidget(self.pagegroup) def createHexOptions(self): self.vvbox = QVBoxLayout() self.vcontainer = QWidget() self.hexgroup = QWidget() self.hexgrid = QGridLayout() groupebylabel = QLabel("Groupe by:") self.groupeby = QComboBox() self.groupeby.addItem("1") self.groupeby.addItem("2") self.groupeby.addItem("4") offsetlabel = QLabel("Offset as") self.offsetas = QComboBox() self.offsetas.addItem("Hexadecimal") self.offsetas.addItem("Decimal") # self.hexgrid.addWidget(groupebylabel, 0, 0) # self.hexgrid.addWidget(self.groupeby, 1, 0) self.hexgrid.addWidget(offsetlabel, 0, 0) self.hexgrid.addWidget(self.offsetas, 0, 1) # self.hexgrid.addWidget(self.fill, 2, 0) # self.hexgrid.setRowStretch(2, 1) self.hexgroup.setLayout(self.hexgrid) self.vvbox.addWidget(self.hexgroup) self.createPageOptions() self.vcontainer.setLayout(self.vvbox) self.optab.insertTab(0, self.vcontainer, "General") # self.vbox.addWidget(self.hexgroup) #Offset as decimal / hexadecimal def createPixelOptions(self): self.pixgroup = QWidget() self.pixgrid = QGridLayout() formatlabel = QLabel("Format :") self.format = QComboBox() self.format.addItem("RGB") self.format.addItem("Alpha RGB") self.format.addItem("Indexed 8bit") self.format.addItem("Mono") self.connect(self.format, SIGNAL("currentIndexChanged(const QString)"), self.formatChanged) colorlabel = QLabel("Indexed Color :") self.icolor = QComboBox() self.icolor.addItem("Green") self.icolor.addItem("Red") self.icolor.addItem("Blue") self.icolor.addItem("Ascii") self.icolor.addItem("256") self.icolor.setEnabled(False) slidelabel = QLabel("Resolution : ") self.sliderspin = QSpinBox(self) self.sliderspin.setMinimum(64) self.sliderspin.setMaximum(1024) self.sliderspin.setValue(self.heditor.wpixel.view.w) self.connect(self.sliderspin, SIGNAL("valueChanged(int)"), self.slidermoved) self.slider = QSlider(Qt.Horizontal) self.slider.setMinimum(64) self.slider.setMaximum(1024) self.slider.setValue(self.heditor.wpixel.view.w) self.slider.setSingleStep(1) self.zoomlabel = QLabel("Scale factor : 1") self.zoom = QSlider(Qt.Horizontal) self.zoom.setMinimum(1) self.zoom.setMaximum(5) self.zoom.setValue(1) self.zoom.setSingleStep(1) self.zoom.setTickInterval(1) self.zoom.setTickPosition(QSlider.TicksBelow) self.connect(self.slider, SIGNAL("sliderMoved(int)"), self.slidermoved) self.connect(self.zoom, SIGNAL("sliderMoved(int)"), self.scale) self.pixgrid.addWidget(formatlabel, 0, 0) self.pixgrid.addWidget(self.format, 0, 1) self.pixgrid.addWidget(colorlabel, 1, 0) self.pixgrid.addWidget(self.icolor, 1, 1) self.pixgrid.addWidget(slidelabel, 2, 0) self.pixgrid.addWidget(self.sliderspin, 2, 1, Qt.AlignLeft) self.pixgrid.addWidget(self.slider, 3, 0) self.pixgrid.addWidget(self.zoomlabel, 4, 0, Qt.AlignLeft) self.pixgrid.addWidget(self.zoom, 5, 0) self.pixgrid.addWidget(self.fill, 6, 0) self.pixgrid.setRowStretch(6, 1) self.pixgroup.setLayout(self.pixgrid) self.optab.insertTab(1, self.pixgroup, "Pixel") def setSliderLabel(self, value): cvalue = QString() cvalue = "%2.d" % value self.sliderlabel.setText(cvalue) def setZoomLabel(self, value): zvalue = QString("Scale factor : ") zvalue += "%2.d" % value self.zoomlabel.setText(zvalue) def createButtons(self): self.applyB = QPushButton("Apply") self.connect(self.applyB, SIGNAL('clicked()'), self.apply) self.vbox.addWidget(self.applyB) def checkValue(self, value): try: n = int(value) return n except ValueError: return -1 def apply(self): #PAGE CHECK pagesize = self.sizeEdit.value() headsize = self.headEdit.value() sparesize = self.spareEdit.value() pagesperblock = self.checkValue(self.pagesperblock.currentText()) if (pagesize < 0) or (headsize < 0) or (sparesize < 0) or (pagesperblock < 0): print "Wrong values" else: offas = self.offsetas.currentText() if offas == "Decimal": self.heditor.decimalview = True elif offas == "Hexadecimal": self.heditor.decimalview = False #Hexview refresh self.heditor.readOffset(self.heditor.currentOffset) #Pageview refresh if self.indic.currentText() == "Offset": self.heditor.pageOffView = True else: self.heditor.pageOffView = False self.heditor.refreshPageValues(headsize, pagesize, sparesize, pagesperblock) if self.heditor.wpage.scroll: self.heditor.wpage.scroll.refreshValues(self.heditor.pagesPerBlock, self.heditor.pageSize) self.heditor.wpage.view.refreshAllContent() #PageView scrollbar refres #Pixel View refresh format = self.format.currentText() if format == "Indexed 8bit": self.heditor.wpixel.view.format = 0 elif format == "Mono": self.heditor.wpixel.view.format = 1 elif format == "RGB": self.heditor.wpixel.view.format = 2 elif format == "Alpha RGB": self.heditor.wpixel.view.format = 3 if self.heditor.wpixel.scroll: self.heditor.wpixel.scroll.refreshValues() #Color icolor = self.icolor.currentText() if icolor == "Red": self.heditor.wpixel.view.icolor = 0 elif icolor == "Green": self.heditor.wpixel.view.icolor = 1 elif icolor == "Blue": self.heditor.wpixel.view.icolor = 2 elif icolor == "Ascii": self.heditor.wpixel.view.icolor = 3 elif icolor == "256": self.heditor.wpixel.view.icolor = 4 pixoffset = self.heditor.wpixel.view.currentOffset self.heditor.wpixel.view.read_image(pixoffset) def slidermoved(self, value): pixoffset = self.heditor.wpixel.view.currentOffset self.heditor.wpixel.view.w = value self.sliderspin.setValue(value) # self.setSliderLabel(value) self.heditor.wpixel.view.read_image(pixoffset) if self.heditor.wpixel.scroll: self.heditor.wpixel.scroll.refreshValues() # print value def scale(self, value): self.setZoomLabel(value) self.heditor.wpixel.view.scale = value pixoffset = self.heditor.wpixel.view.currentOffset self.heditor.wpixel.view.read_image(pixoffset) def formatChanged(self, format): if format == "Indexed 8bit": self.icolor.setEnabled(True) else: self.icolor.setEnabled(False) def keyPressEvent(self, kEvent): key = kEvent.key() if key == Qt.Key_Return or key == Qt.Key_Enter: self.apply()
class Tool(QToolBar): def __init__(self,parent): QToolBar.__init__(self,parent) self.parent = parent self.action_NewProject = QAction(Icons.newprj, 'Project', self) self.action_NewProject.triggered.connect(self.parent.treeWidget.newProject) self.action_NewProject.setToolTip("Create a New Project") self.action_Open = QAction(Icons.open, 'Open', self) self.action_Open.triggered.connect(self.parent.fileOpen) self.action_Open.setToolTip("Open File") self.action_Save = QAction(Icons.save, 'Save', self) self.action_Save.setShortcut('Ctrl+S') self.action_Save.triggered.connect(self.parent.fileSave) self.action_Save.setToolTip("Save Current File") self.action_SaveAll = QAction(Icons.saveall, 'SaveAll', self) self.action_SaveAll.setShortcut('Ctrl+A') self.action_SaveAll.triggered.connect(self.parent.fileSaveAll) self.action_SaveAll.setToolTip("Save All Files") self.action_Build = QAction(Icons.thread_view, 'Build', self) self.action_Build.setShortcut('Ctrl+B') self.action_Build.triggered.connect(self.parent.build_project) self.action_Debug = QAction(Icons.debug_exec, 'Debug', self) self.action_Refresh = QAction(Icons.refresh_tab, 'Refresh', self) self.action_Refresh.triggered.connect(self.parent.treeWidget.refreshCurrentProject) self.action_Run = QAction(Icons.run, 'Run', self) self.action_Run.setShortcut('Ctrl+R') self.action_Run.triggered.connect(self.parent.adb.run) self.action_RunFile = QAction(Icons.go, 'Cmd', self) self.action_RunFile.triggered.connect(self.parent.openCommand) self.parent.runButton.clicked.connect(self.parent.command.setCmdLine) self.action_Stop = QAction(Icons.stop, 'Stop', self) self.action_Stop.setShortcut('Ctrl+Q') self.action_Stop.triggered.connect(self.parent.adb.stop) self.action_Design = QAction(Icons.color_palette, 'Design', self) self.action_Design.triggered.connect(self.parent.design) self.action_Level = QAction(Icons.cmpC_pal, 'Level', self) self.action_Level.triggered.connect(self.parent.level) self.action_Todo = QAction(Icons.task_set, 'Todo', self) self.action_Todo.triggered.connect(self.parent.todo) self.action_Help = QAction(Icons.toc_open, 'Help', self) self.action_Help.triggered.connect(self.parent.help) men = QMenu() #Threshold Slider self.threshSlider = QSlider() self.threshSlider.setTickPosition(QSlider.TicksLeft) self.threshSlider.setOrientation(Qt.Horizontal) self.threshSlider.setValue(config.thresh()) self.threshSlider.setMinimum(0) self.threshSlider.setMaximum(5) self.threshSlider.valueChanged.connect(self.parent.setThreshold) self.threshSliderAction = QWidgetAction(men) self.threshSliderAction.setDefaultWidget(self.threshSlider) #TabsWidth Slider self.tabsSlider = QSlider() self.tabsSlider.setTickPosition(QSlider.TicksLeft) self.tabsSlider.setOrientation(Qt.Horizontal) self.tabsSlider.setValue(config.tabwidth()) self.tabsSlider.setMinimum(0) self.tabsSlider.setMaximum(8) self.tabsSlider.valueChanged.connect(self.parent.setTabWidth) self.tabsSliderAction = QWidgetAction(men) self.tabsSliderAction.setDefaultWidget(self.tabsSlider) #iconSize Slider self.iconSlider = QSlider() self.iconSlider.setTickPosition(QSlider.TicksLeft) self.iconSlider.setOrientation(Qt.Horizontal) self.iconSlider.setValue(config.iconSize()) self.iconSlider.setMinimum(16) self.iconSlider.setMaximum(32) self.iconSlider.setSingleStep(2) self.iconSlider.valueChanged.connect(self.setIcon) self.iconSliderAction = QWidgetAction(men) self.iconSliderAction.setDefaultWidget(self.iconSlider) '''Font Button''' self.fontCombo = QFontComboBox() self.fontCombo.currentFontChanged.connect(self.parent.setFont) self.fontCombo.setCurrentFont(QFont(config.fontName())) self.fontComboMenu = QWidgetAction(men) self.fontComboMenu.setDefaultWidget(self.fontCombo) '''Font Size''' self.fontSizeCombo = QComboBox() for size in range(1,40): self.fontSizeCombo.addItem(str(size)) self.fontSizeCombo.setCurrentIndex(config.fontSize()) self.fontSizeCombo.currentIndexChanged.connect(self.parent.setFontSize) self.fontSizeComboMenu = QWidgetAction(men) self.fontSizeComboMenu.setDefaultWidget(self.fontSizeCombo) action_explorer = QAction("Show Explorer",self) action_explorer.triggered.connect(self.parent.exp) action_console = QAction("Show Console",self) action_console.triggered.connect(self.parent.cmd) action_designer = QAction("Show Designer",self) action_designer.triggered.connect(self.parent.design) action_Indentation = QAction("Indentation Guides",self) action_Indentation.triggered.connect(self.parent.setIndent) action_WhiteSpace = QAction("Show WhiteSpace",self) action_WhiteSpace.triggered.connect(self.parent.setWhiteSpace) action_EndLine = QAction("Show End of Lines",self) action_EndLine.triggered.connect(self.parent.setEndLine) action_Margin = QAction("Line Numbers",self) action_Margin.triggered.connect(self.parent.setMargin) action_ToolLabel = QAction("Tool Labels",self) action_ToolLabel.triggered.connect(self.setToolLabel) action_Android = QAction(Icons.android,'Android', self) action_Android.triggered.connect(self.parent.android) action_Ant = QAction(Icons.ant_view,'Ant', self) action_Ant.triggered.connect(self.parent.antt) action_Squirrel = QAction(Icons.nut,'Squirrel', self) action_Squirrel.triggered.connect(self.parent.squirrel) action_Ios1 = QAction(Icons.ios,'iOS', self) action_Update = QAction("Update",self) action_Update.triggered.connect(self.parent.update) '''Encoding''' encodingGroup = QActionGroup(self) encodingGroup.setExclusive(True) action_Ascii = QAction("Ascii",encodingGroup) action_Ascii.setCheckable(True) action_Unicode = QAction("Unicode",encodingGroup) action_Unicode.setCheckable(True) encodingGroup.addAction(action_Ascii) encodingGroup.addAction(action_Unicode) encodingGroup.selected.connect(self.parent.setEncoding) if(config.encoding() == Encoding.ASCII): action_Ascii.setChecked(True) else: action_Unicode.setChecked(True) men.addAction(action_Android) men.addAction(action_Ant) men.addAction(action_Squirrel) men.addAction(action_Ios1) men.addAction(action_Update) men.addSeparator() men.addAction(action_explorer) men.addAction(action_console) men.addAction(action_designer) men.addAction(action_Indentation) men.addAction(action_WhiteSpace) men.addAction(action_EndLine) men.addAction(action_Margin) men.addAction(action_ToolLabel) men.addSeparator() men.addActions(encodingGroup.actions()) men.addSeparator() head_font = QLabel("Font---------------------") fnt = head_font.font() fnt.setBold(True) head_font.setFont(fnt) head_fontWidgetAction = QWidgetAction(men) head_fontWidgetAction.setDefaultWidget(head_font) men.addAction(head_fontWidgetAction) men.addAction(self.fontComboMenu) men.addAction(self.fontSizeComboMenu) men.addSeparator() men.addAction(QAction("TabWidth",self)) men.addAction(self.tabsSliderAction) men.addSeparator() men.addAction(QAction("Threshold",self)) men.addAction(self.threshSliderAction) #men.addAction(QAction("Icon Size",self)) #men.addAction(self.iconSliderAction) self.action_Options = QAction(Icons.emblem_system, 'Options', self) self.action_Options.setMenu(men) self.action_Full = QAction(Icons.fullscreen, 'Full', self) self.action_Full.setShortcut('Shift+Enter') self.action_Full.triggered.connect(self.parent.full) self.modeGroup = QActionGroup(self) self.modeGroup.setExclusive(True) self.modeGroup.selected.connect(self.parent.setMode) self.action_Squirrel = QAction(Icons.nut, 'Squ', self.modeGroup) self.action_Squirrel.setCheckable(True) self.action_Emo = QAction(Icons.emo, 'Emo', self.modeGroup) self.action_Emo.setCheckable(True) self.action_And = QAction(Icons.android, 'Android', self.modeGroup) self.action_And.setCheckable(True) self.action_Ios = QAction(Icons.ios, 'ios', self.modeGroup) self.action_Ios.setCheckable(True) self.modeGroup.addAction(self.action_Squirrel) self.modeGroup.addAction(self.action_Emo) self.modeGroup.addAction(self.action_And) self.modeGroup.addAction(self.action_Ios) self.action_Style = QAction(Icons.style, 'Style', self) men1 = QMenu() self.styleslist = [] self.style1 = QAction("All Hallow's Eve",self) self.style1.triggered.connect(lambda:self.parent.style_clicked(1)) self.style1.setCheckable(True) self.style2 = QAction("Amy",self) self.style2.triggered.connect(lambda:self.parent.style_clicked(2)) self.style2.setCheckable(True) self.style3 = QAction("Aptana Studio",self) self.style3.triggered.connect(lambda:self.parent.style_clicked(3)) self.style3.setCheckable(True) self.style4 = QAction("Bespin",self) self.style4.triggered.connect(lambda:self.parent.style_clicked(4)) self.style4.setCheckable(True) self.style5 = QAction("Blackboard",self) self.style5.triggered.connect(lambda:self.parent.style_clicked(5)) self.style5.setCheckable(True) self.style6 = QAction("Choco",self) self.style6.triggered.connect(lambda:self.parent.style_clicked(6)) self.style6.setCheckable(True) self.style7 = QAction("Cobalt",self) self.style7.triggered.connect(lambda:self.parent.style_clicked(7)) self.style7.setCheckable(True) self.style8 = QAction("Dawn",self) self.style8.triggered.connect(lambda:self.parent.style_clicked(8)) self.style8.setCheckable(True) self.style9 = QAction("Eclipse",self) self.style9.triggered.connect(lambda:self.parent.style_clicked(9)) self.style9.setCheckable(True) self.styleslist.append(self.style1) self.styleslist.append(self.style2) self.styleslist.append(self.style3) self.styleslist.append(self.style4) self.styleslist.append(self.style5) self.styleslist.append(self.style6) self.styleslist.append(self.style7) self.styleslist.append(self.style8) self.styleslist.append(self.style9) men1.addActions(self.styleslist) self.action_Style.setMenu(men1) self.styleslist[self.parent.styleIndex].setChecked(True) self.action_Stop.setDisabled(True) self.setToolLabel() self.setAllowedAreas(Qt.AllToolBarAreas) #self.setFixedHeight(40) #self.setIconSize(QSize(config.iconSize(),config.iconSize())) self.addAction(self.action_NewProject) self.addAction(self.action_Open) self.addAction(self.action_Save) self.addAction(self.action_SaveAll) #self.addAction(self.action_Refresh) self.addSeparator() self.addAction(self.action_Build) self.addAction(self.action_Run) self.addAction(self.action_RunFile) self.addAction(self.action_Stop) self.addAction(self.action_Debug) self.addSeparator() self.addAction(self.action_Design) self.addAction(self.action_Level) self.addAction(self.action_Todo) self.addAction(self.action_Options) self.addAction(self.action_Style) self.addSeparator() self.addAction(self.action_Help) self.addAction(self.action_Full) self.addSeparator() self.addActions(self.modeGroup.actions()) if(config.mode() == 0): self.action_Squirrel.setChecked(True) elif(config.mode() == 1): self.action_Emo.setChecked(True) elif(config.mode() == 2): self.action_And.setChecked(True) elif(config.mode() == 3): self.action_Ios.setChecked(True) def setIcon(self,val): config.setIconSize(val) self.setIconSize(QSize(val,val)) def setToolLabel(self): if (config.toolLabel()): self.setToolButtonStyle(Qt.ToolButtonIconOnly) self.setIconSize(QSize(24,24)) else: self.setIconSize(QSize(16,16)) self.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) '''Important for multiple callbacks in for loop''' def make_callback(self, param): return lambda:self.parent.setFontName(param)
class Ui_Form (QWidget): ''' Ui class. Generated with pyuic4. ''' def __init__ (self, parent=None): QWidget.__init__(self, parent) self.timer = QTimer (self) self.image = QImage (720, 450, QImage.Format_RGB888) self.__engine = REngineThread () self.__model = Model () self.__fsm = DebugStateMachine (self) def wireEngineUp (self): ''' this method connects the REngine's signals. ''' self.connect (self.__engine, SIGNAL ("update (float)"), self.updateImage) self.connect (self.__engine, SIGNAL ("thread_completed()"), self.__fsm.finaliseRender) self.connect (self.__engine, SIGNAL ("inters_created (PyQt_PyObject, PyQt_PyObject)"), self.widget.addIntersection) self.connect (self.__engine, SIGNAL ("vector_created (PyQt_PyObject, PyQt_PyObject, QString)"), self.widget.addArrow) self.connect (self.__engine, SIGNAL ("line_created (PyQt_PyObject, PyQt_PyObject, QString)"), self.widget.addLine) def wireOGLViewerUp (self): ''' this method connects the REngine's signals. ''' self.widget.setModel (self.__model) QObject.connect (self.widget, SIGNAL ("MatrixChanged (PyQt_PyObject)"), self.displayGLMatrix) # call the function run regularly when the focus is on it. (60 FPS if interval = 20) QObject.connect (self.timer, SIGNAL ('timeout()'), self.widget.run) def freezeGLFrameRate (self): self.timer.stop () def speedUpGLFrameRate (self): self.timer.start () self.timer.setInterval (20) def setupUi (self, Form): font = QFont () font.setPointSize (9) font.setBold (False) font.setWeight (50) sizePolicy = QSizePolicy (QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch (0) sizePolicy.setVerticalStretch (0) Form.setObjectName (_fromUtf8("Form")) Form.resize (971, 930) self.plainTextEdit = QPlainTextEdit (Form) self.plainTextEdit.setGeometry (QRect (740, 280, 221, 611)) self.plainTextEdit.setObjectName (_fromUtf8 ("plainTextEdit")) self.plainTextEdit.setFont (font) self.widget = OGLViewer (Form) self.widget.setUi_Form (self) self.widget.setGeometry (QRect (10, 10, 720, 450)) sizePolicy.setHeightForWidth (self.widget.sizePolicy().hasHeightForWidth()) self.widget.setSizePolicy (sizePolicy) self.widget.setObjectName (_fromUtf8 ("widget")) self.wireOGLViewerUp () self.wireEngineUp () self.label_view = QLabel (Form) self.label_view.setGeometry (QRect (10, 470, 720, 450)) sizePolicy.setHeightForWidth (self.label_view.sizePolicy().hasHeightForWidth()) self.label_view.setSizePolicy (sizePolicy) self.label_view.setObjectName (_fromUtf8 ("label_view")) self.initLabel () self.pixmap_item = self.label_view.setPixmap (QPixmap.fromImage (self.image)) # buttons definitions self.renderBtn = QPushButton (Form) self.pauseBtn = QPushButton (Form) self.stopBtn = QPushButton (Form) self.upBtn = QPushButton (Form) self.downBtn = QPushButton (Form) self.moreDownBtn = QPushButton (Form) self.moreUpBtn = QPushButton (Form) self.rightBtn = QPushButton (Form) self.moreRightBtn = QPushButton (Form) self.leftBtn = QPushButton (Form) self.furtherLeft = QPushButton (Form) self.grid_switch = QPushButton (Form) buttons_properties_list = [[self.renderBtn, True, QRect (740, 140, 61, 21), "render"], [self.pauseBtn, False, QRect (740, 120, 61, 21), "pause"], [self.stopBtn, False, QRect (740, 100, 61, 21), "stop"], [self.upBtn, False, QRect (820, 120, 21, 21), "one_row_up"], [self.downBtn, False, QRect (820, 140, 21, 21), "one_row_down"], [self.moreDownBtn, False, QRect (820, 160, 21, 21), "ten_rows_down"], [self.moreUpBtn, False, QRect (820, 100, 21, 21), "ten_rows_up"], [self.rightBtn, False, QRect (780, 180, 21, 21), "one_column_right"], [self.moreRightBtn, False, QRect (800, 180, 21, 21), "ten_columns_right"], [self.leftBtn, False, QRect (760, 180, 21, 21), "one_column_left"], [self.furtherLeft, False, QRect (740, 180, 21, 21), "ten_columns_left"], [self.grid_switch, False, QRect (870, 230, 91, 31), "grid_switch"]] for button in buttons_properties_list: button[0].setEnabled (button[1]) button[0].setGeometry (button[2]) button[0].setFont (font) button[0].setObjectName (_fromUtf8 (button[3])) # other UI elements self.progressBar = QProgressBar (Form) self.progressBar.setGeometry (QRect (740, 901, 221, 20)) self.progressBar.setProperty ("value", 0) self.progressBar.setObjectName (_fromUtf8("progressBar")) self.progressBar.setMinimum (0) self.progressBar.setMaximum (100) self.slider_label = QLabel (Form) self.slider_label.setGeometry (QRect(900, 260, 61, 16)) self.slider_label.setFont(font) self.slider_label.setObjectName (_fromUtf8("slider_label")) self.slider_label.setEnabled (True) self.arrowSizeSlider = QSlider (Form) self.arrowSizeSlider.setGeometry (QRect (740, 258, 151, 22)) self.arrowSizeSlider.setMinimum (2) self.arrowSizeSlider.setMaximum (40) self.arrowSizeSlider.setSingleStep (1) self.arrowSizeSlider.setProperty ("value", 4) self.arrowSizeSlider.setOrientation (Qt.Horizontal) self.arrowSizeSlider.setObjectName (_fromUtf8("arrowSizeSlider")) self.retranslateUi (Form) QMetaObject.connectSlotsByName (Form) def retranslateUi (self, Form): Form.setWindowTitle (_translate ("Form", "RayTracing Debugging Tool", None)) self.renderBtn.setText (_translate ("Form", "Render", None)) self.pauseBtn.setText (_translate ("Form", "Pause", None)) self.stopBtn.setText (_translate ("Form", "Stop", None)) self.upBtn.setText (_translate ("Form", "^", None)) self.downBtn.setText (_translate ("Form", "v", None)) self.moreDownBtn.setText (_translate ("Form", "+", None)) self.moreUpBtn.setText (_translate ("Form", "-", None)) self.rightBtn.setText (_translate ("Form", ">", None)) self.moreRightBtn.setText (_translate ("Form", "+", None)) self.leftBtn.setText (_translate ("Form", "<", None)) self.furtherLeft.setText (_translate ("Form", "-", None)) self.grid_switch.setText (_translate ("Form", "Grid on/off", None)) self.slider_label.setText (_translate ("Form", "Arrows size", None)) self.connect (self.renderBtn, SIGNAL ("clicked()"), self.__fsm.startRendering) self.connect (self.pauseBtn, SIGNAL ("clicked()"), self.__fsm.pauseRendering) self.connect (self.stopBtn, SIGNAL ("clicked()"), self.__fsm.stopRendering) self.connect (self.arrowSizeSlider, SIGNAL ("sliderMoved(int)"), self.resizeArrows) def initLabel (self): color = QColor (250, 250, 250) self.image.fill (color) ''' # test init for i in range (0, 200, 20): for x in range (i, i+20): for y in range (i, i+20): self.image.setPixel (x,y, qRgb (0, 0, 0)) ''' def enableUIButtons (self, boolean_dict): ''' method used by the debug state machine to manage the greyed-out state of buttons. ''' b_dict = dict (boolean_dict) self.renderBtn.setEnabled (b_dict['renderBtn']) self.pauseBtn.setEnabled (b_dict['pauseBtn']) self.stopBtn.setEnabled (b_dict['stopBtn']) self.upBtn.setEnabled (b_dict['upBtn']) self.downBtn.setEnabled (b_dict['downBtn']) self.moreDownBtn.setEnabled (b_dict['moreDownBtn']) self.moreUpBtn.setEnabled (b_dict['moreUpBtn']) self.rightBtn.setEnabled (b_dict['rightBtn']) self.moreRightBtn.setEnabled (b_dict['moreRightBtn']) self.leftBtn.setEnabled (b_dict['leftBtn']) self.furtherLeft.setEnabled (b_dict['furtherLeft']) if b_dict['progressBar'] == 'completed': self.progressBar.setValue (100) elif b_dict['progressBar'] == 'reset': self.progressBar.reset () def addScreenshot (self): ''' it grabs a screenshot of OpenGL viewer and add it into the QImage instance. ''' self.image = self.widget.grabFrameBuffer () self.pixmap_item = self.label_view.setPixmap (QPixmap.fromImage (self.image)) def prepAndStartEngineUp (self): ''' it preps the engine and start it up. ''' self.__engine.setImage (self.image) self.__engine.setCameraNormalMatrix (self.widget.getNormalMatrix(), self.widget.getFovy ()) self.__engine.setModel (self.__model) self.__engine.start () def addCamera (self): self.widget.addCamera () def setIsStoppedFlag (self, boo): self.__engine.setIsStoppedFlag (boo) def setIsPausedFlag (self, boo): self.__engine.setIsPausedFlag (boo) def changeRenderBtnName (self, title): self.renderBtn.setText (_translate ("Form", title, None)) # listeners - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - def resizeArrows (self, e): self.widget.changeArrowsSize (e*0.5) def updateImage (self, e): self.pixmap_item = self.label_view.setPixmap (QPixmap.fromImage (self.image)) self.progressBar.setValue (int(100*e)) def displayGLMatrix (self, e): ''' this method is registered to the MatrixChanged event fired from the OGLViewer component. It prints the model matrix. Only for debugging purposes. ''' pass
class PreferencesDialogBase(QDialog): def __init__(self, parent, app): flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint QDialog.__init__(self, parent, flags) self.app = app self._setupUi() self.connect(self.filterHardnessSlider, SIGNAL("valueChanged(int)"), self.filterHardnessLabel.setNum) self.connect(self.buttonBox, SIGNAL('clicked(QAbstractButton*)'), self.buttonClicked) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) def _setupScanTypeBox(self, labels): self.scanTypeHLayout = QHBoxLayout() self.scanTypeLabel = QLabel(self) self.scanTypeLabel.setText(tr("Scan Type:")) self.scanTypeLabel.setMinimumSize(QSize(100, 0)) self.scanTypeLabel.setMaximumSize(QSize(100, 16777215)) self.scanTypeHLayout.addWidget(self.scanTypeLabel) self.scanTypeComboBox = QComboBox(self) for label in labels: self.scanTypeComboBox.addItem(label) self.scanTypeHLayout.addWidget(self.scanTypeComboBox) self.widgetsVLayout.addLayout(self.scanTypeHLayout) def _setupFilterHardnessBox(self): self.filterHardnessHLayout = QHBoxLayout() self.filterHardnessLabel = QLabel(self) self.filterHardnessLabel.setText(tr("Filter Hardness:")) self.filterHardnessLabel.setMinimumSize(QSize(0, 0)) self.filterHardnessHLayout.addWidget(self.filterHardnessLabel) self.filterHardnessVLayout = QVBoxLayout() self.filterHardnessVLayout.setSpacing(0) self.filterHardnessHLayoutSub1 = QHBoxLayout() self.filterHardnessHLayoutSub1.setSpacing(12) self.filterHardnessSlider = QSlider(self) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.filterHardnessSlider.sizePolicy().hasHeightForWidth()) self.filterHardnessSlider.setSizePolicy(sizePolicy) self.filterHardnessSlider.setMinimum(1) self.filterHardnessSlider.setMaximum(100) self.filterHardnessSlider.setTracking(True) self.filterHardnessSlider.setOrientation(Qt.Horizontal) self.filterHardnessHLayoutSub1.addWidget(self.filterHardnessSlider) self.filterHardnessLabel = QLabel(self) self.filterHardnessLabel.setText("100") self.filterHardnessLabel.setMinimumSize(QSize(21, 0)) self.filterHardnessHLayoutSub1.addWidget(self.filterHardnessLabel) self.filterHardnessVLayout.addLayout(self.filterHardnessHLayoutSub1) self.filterHardnessHLayoutSub2 = QHBoxLayout() self.filterHardnessHLayoutSub2.setContentsMargins(-1, 0, -1, -1) self.moreResultsLabel = QLabel(self) self.moreResultsLabel.setText(tr("More Results")) self.filterHardnessHLayoutSub2.addWidget(self.moreResultsLabel) spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.filterHardnessHLayoutSub2.addItem(spacerItem) self.fewerResultsLabel = QLabel(self) self.fewerResultsLabel.setText(tr("Fewer Results")) self.filterHardnessHLayoutSub2.addWidget(self.fewerResultsLabel) self.filterHardnessVLayout.addLayout(self.filterHardnessHLayoutSub2) self.filterHardnessHLayout.addLayout(self.filterHardnessVLayout) def _setupBottomPart(self): # The bottom part of the pref panel is always the same in all editions. self.fontSizeLabel = QLabel(tr("Font size:")) self.fontSizeSpinBox = QSpinBox() self.fontSizeSpinBox.setMinimum(5) self.widgetsVLayout.addLayout( horizontalWrap([self.fontSizeLabel, self.fontSizeSpinBox, None])) self.languageLabel = QLabel(tr("Language:"), self) self.languageComboBox = QComboBox(self) for lang in SUPPORTED_LANGUAGES: self.languageComboBox.addItem(LANGNAMES[lang]) self.widgetsVLayout.addLayout( horizontalWrap([self.languageLabel, self.languageComboBox, None])) self.copyMoveLabel = QLabel(self) self.copyMoveLabel.setText(tr("Copy and Move:")) self.widgetsVLayout.addWidget(self.copyMoveLabel) self.copyMoveDestinationComboBox = QComboBox(self) self.copyMoveDestinationComboBox.addItem(tr("Right in destination")) self.copyMoveDestinationComboBox.addItem(tr("Recreate relative path")) self.copyMoveDestinationComboBox.addItem(tr("Recreate absolute path")) self.widgetsVLayout.addWidget(self.copyMoveDestinationComboBox) self.customCommandLabel = QLabel(self) self.customCommandLabel.setText( tr("Custom Command (arguments: %d for dupe, %r for ref):")) self.widgetsVLayout.addWidget(self.customCommandLabel) self.customCommandEdit = QLineEdit(self) self.widgetsVLayout.addWidget(self.customCommandEdit) def _setupAddCheckbox(self, name, label, parent=None): if parent is None: parent = self cb = QCheckBox(parent) cb.setText(label) setattr(self, name, cb) def _setupPreferenceWidgets(self): # Edition-specific pass def _setupUi(self): self.setWindowTitle(tr("Preferences")) self.resize(304, 263) self.setSizeGripEnabled(False) self.setModal(True) self.mainVLayout = QVBoxLayout(self) self.widgetsVLayout = QVBoxLayout() self._setupPreferenceWidgets() self.mainVLayout.addLayout(self.widgetsVLayout) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok | QDialogButtonBox.RestoreDefaults) self.mainVLayout.addWidget(self.buttonBox) if (not ISOSX) and (not ISLINUX): self.mainVLayout.removeWidget(self.ignoreHardlinkMatches) self.ignoreHardlinkMatches.setHidden(True) def _load(self, prefs, setchecked): # Edition-specific pass def _save(self, prefs, ischecked): # Edition-specific pass def load(self, prefs=None): if prefs is None: prefs = self.app.prefs self.filterHardnessSlider.setValue(prefs.filter_hardness) self.filterHardnessLabel.setNum(prefs.filter_hardness) setchecked = lambda cb, b: cb.setCheckState(Qt.Checked if b else Qt.Unchecked) setchecked(self.mixFileKindBox, prefs.mix_file_kind) setchecked(self.useRegexpBox, prefs.use_regexp) setchecked(self.removeEmptyFoldersBox, prefs.remove_empty_folders) setchecked(self.ignoreHardlinkMatches, prefs.ignore_hardlink_matches) setchecked(self.debugModeBox, prefs.debug_mode) self.copyMoveDestinationComboBox.setCurrentIndex( prefs.destination_type) self.customCommandEdit.setText(prefs.custom_command) self.fontSizeSpinBox.setValue(prefs.tableFontSize) try: langindex = SUPPORTED_LANGUAGES.index(self.app.prefs.language) except ValueError: langindex = 0 self.languageComboBox.setCurrentIndex(langindex) self._load(prefs, setchecked) def save(self): prefs = self.app.prefs prefs.filter_hardness = self.filterHardnessSlider.value() ischecked = lambda cb: cb.checkState() == Qt.Checked prefs.mix_file_kind = ischecked(self.mixFileKindBox) prefs.use_regexp = ischecked(self.useRegexpBox) prefs.remove_empty_folders = ischecked(self.removeEmptyFoldersBox) prefs.ignore_hardlink_matches = ischecked(self.ignoreHardlinkMatches) prefs.debug_mode = ischecked(self.debugModeBox) prefs.destination_type = self.copyMoveDestinationComboBox.currentIndex( ) prefs.custom_command = str(self.customCommandEdit.text()) prefs.tableFontSize = self.fontSizeSpinBox.value() lang = SUPPORTED_LANGUAGES[self.languageComboBox.currentIndex()] oldlang = self.app.prefs.language if oldlang not in SUPPORTED_LANGUAGES: oldlang = 'en' if lang != oldlang: QMessageBox.information( self, "", tr("dupeGuru has to restart for language changes to take effect." )) self.app.prefs.language = lang self._save(prefs, ischecked) #--- Events def buttonClicked(self, button): role = self.buttonBox.buttonRole(button) if role == QDialogButtonBox.ResetRole: self.resetToDefaults()