class Main: def __init__(self): self.main_win = QMainWindow() self.ui = Ui_MainWindow() self.ui.setupUi(self.main_win) self.ui.stackedWidget.setCurrentWidget(self.ui.home) self.ui.nav_home_btn.clicked.connect(self.showHome) self.ui.nav_scan_btn.clicked.connect(self.showPortScan) self.ui.nav_ip_btn.clicked.connect(self.showIpScan) self.ui.nav_terminal_btn.clicked.connect(self.showTerminal) def show(self): self.main_win.showMaximized() def showHome(self): self.ui.stackedWidget.setCurrentWidget(self.ui.home) def showPortScan(self): self.ui.stackedWidget.setCurrentWidget(self.ui.port_scan) def showIpScan(self): self.ui.stackedWidget.setCurrentWidget(self.ui.ip_scan) def showTerminal(self): self.ui.stackedWidget.setCurrentWidget(self.ui.terminal)
class mainWindow(QMainWindow): def __init__(self, scaleRate): super(mainWindow, self).__init__(None) self.ui = Ui_MainWindow() self.ui.setupUi(self,scaleRate) # 把所有控件大小和位置都乘以Windows缩放比例来适配Windows缩放 self.setupIcon() # 直接通过base64把图标写入程序,避免pyinstaller打包后图标失效 self.dumpingdialog = dumpingDialog(self,self.icon) self.initSignal() self.show() def setupIcon(self): self.pmap = QPixmap() self.pmap.loadFromData(QByteArray.fromBase64(iconb64)) self.icon = QIcon(self.pmap) self.setWindowIcon(self.icon) def initSignal(self): self.ui.commandLinkButton.clicked.connect(self.dumper) def dumper(self): files,fileType = QFileDialog.getOpenFileNames(self, "请选择ncm文件", "./", "NeteaseCloudMusic Files (*.ncm)") if files: outputPath = QFileDialog.getExistingDirectory(self, '请选择输出文件夹', '/'.join(files[0].split('/')[:-1])) # 初始输出文件夹为第一个ncm文件所在目录 if outputPath: self.dumpingdialog.show() filesTotal, filesDumped = len(files), 0 self.dumpingdialog.ui.label.setText(f'转换中\n{filesDumped}/{filesTotal}') for file in files: dump(file,outputPath+'/'+file.split('/')[-1][:-3]+'mp3') filesDumped += 1 self.dumpingdialog.ui.label.setText(f'转换中\n{filesDumped}/{filesTotal}') self.dumpingdialog.setWindowTitle('转换完毕!') self.dumpingdialog.ui.label.setText('转换完毕!')
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.quitButton.clicked.connect(self.close) self.ui.createTemplateButton.clicked.connect(self.createNewTemplate) self.ui.editLibraryButton.clicked.connect(self.openEditLibrary) self.ui.playMenuButton.clicked.connect(self.openPlayMenu) self.w = None # Create the widget to make a new template. Hide the main window and pass a reference of itself to the # constructor for the newTemplate widget. def createNewTemplate(self): self.hide() self.w = newTemplate(self) self.w.show() def openEditLibrary(self): self.hide() self.w = editLibrary(self) self.w.show() def openPlayMenu(self): self.hide() self.w = playMenu(self) self.w.show()
def main(): app = QtWidgets.QApplication(sys.argv) if check_login(): MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())
class execc: progress_value = 0 stop_progress = False def __init__(self): app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() self.ui = Ui_MainWindow() self.ui.setupUi(MainWindow) self.ui.pushButton_2.clicked.connect(self.submit) self.ui.pushButton_3.clicked.connect(os._exit) MainWindow.show() sys.exit(app.exec_()) def submit(self): try: url1 = self.ui.lineEdit.text() userName = self.ui.lineEdit_2.text() UserCSS = self.ui.lineEdit_3.text() PasswordCSS = self.ui.lineEdit_4.text() SubmitCSS = self.ui.lineEdit_6.text() Rate = float(self.ui.lineEdit_5.text()) if (url1 == "" or userName == "" or UserCSS == "" or PasswordCSS == "" or Rate == "" or SubmitCSS == ""): print("Fill all info") return browser = webdriver.Firefox() # Opens the Browser browser.get(url1) # Open the Target url in browser password = open('passwords.txt' ) # This text file contains most common passwords for pattern in password: # Check all the patterns in password try: userElem = browser.find_element_by_css_selector( UserCSS) # Navigate to UserName Field userElem.send_keys( userName) # Types the Username of target passElem = browser.find_element_by_css_selector( PasswordCSS) # Navigate to Password Field passElem.send_keys(pattern) # Types pattern in password submit = browser.find_element_by_css_selector( SubmitCSS) # Navigate to Submit Button submit.click() # Click on submit button time.sleep(Rate) # Waits for page to get refresh except: print("Successful") # Print Success message break # Breaks the loop password.close() # Close the File except: print('Please fill form Correctly')
class MainWin(QMainWindow): def __init__(self, parent=None): super().__init__(parent=parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setWindowTitle("Wish List") self.WishInterface = WishInterface(session) self.items = [] self.update() self.ui.itemsLW.itemDoubleClicked.connect(self._on_item_clicked) self.ui.createBtn.clicked.connect(self._on_create_clicked) self.ui.deleteAllBtn.clicked.connect(self._on_delete_clicked) def _on_item_clicked(self, item: QListWidgetItem): self.current_item = ItemInfo(self) self.current_item.set_from_item(item) self.current_item.show() def _on_create_clicked(self): self.current_item = ItemInfo(self) self.current_item.set_new() self.current_item.show() def _on_delete_clicked(self): for wish in self.WishInterface.all(): self.WishInterface.delete(wish) self.update() def update(self, *__args): while len(self.items): self.ui.itemsLW.takeItem(0) self.items.pop(0) wishes = self.WishInterface.all() self.items = [f"{wish.id}. {wish.title}" for wish in wishes] self.ui.itemsLW.addItems(self.items)
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.btn_salir.clicked.connect(self.salir) self.ui.btn_agregar.clicked.connect(self.mostrar_agregar) self.ui.btn_comprar.clicked.connect(self.mostrar_comprar) self.ui.btn_mostrar.clicked.connect(self.mostrar_tabla) @Slot() def mostrar_agregar(self): main_window.hide() agregar_window.reiniciarLe() agregar_window.show() @Slot() def mostrar_comprar(self): main_window.hide() comprar_window.reiniciarLe() comprar_window.reiniciarLabel() comprar_window.actualizarProductosTemporales() comprar_window.show() @Slot() def mostrar_tabla(self): main_window.hide() tabla_window.actualizar_tabla() tabla_window.show() @Slot() def salir(self): sys.exit(app.exec_()) def actualizarLabel(self): global ganancias_totales self.ui.label_precio.setText('$ ' + str(ganancias_totales))
class Ui_MultWindow(QtWidgets.QWidget): def setupUi(self, Main): Main.setObjectName("Main") Main.resize(640, 480) self.QtStack = QStackedLayout() self.stack0 = QMainWindow() self.stack1 = QMainWindow() self.stack2 = QMainWindow() self.mainScreen = Ui_MainWindow() self.mainScreen.setupUi(self.stack0) self.registerScreen = Ui_RegisterWindow() self.registerScreen.setupUi(self.stack1) self.searchScreen = Ui_SearchWindow() self.searchScreen.setupUi(self.stack2) self.QtStack.addWidget(self.stack0) self.QtStack.addWidget(self.stack1) self.QtStack.addWidget(self.stack2)
class AQMain(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) # TODO: figure out way to configure for different comm types (TCP, MAVLINK, etc) self.comm = AQSerial() # Default main window conditions self.ui.buttonDisconnect.setEnabled(False) self.ui.buttonConnect.setEnabled(True) self.ui.comPort.setEnabled(True) self.ui.baudRate.setEnabled(True) self.ui.status.setText("Not connected to the AeroQuad") self.availablePorts = [] self.updateComPortSelection() self.updateBaudRates() # Update comm port combo box to use last used comm port defaultComPort = xml.find("./Settings/DefaultComPort").text commIndex = self.ui.comPort.findText(defaultComPort) if commIndex == -1: commIndex = 0 self.ui.comPort.setCurrentIndex(commIndex) # Load splash screen self.subPanel = Ui_splashScreen() self.subPanel.setupUi(self.subPanel) self.ui.subPanel.addWidget(self.subPanel) # Dynamically configure board type menu and subPanel menu from XML configuration file self.selectedBoardType = self.configureBoardTypeMenu() self.configureSubPanelMenu(self.selectedBoardType) self.activeSubPanel = None # Connect GUI slots and signals self.ui.buttonConnect.clicked.connect(self.connect) self.ui.buttonDisconnect.clicked.connect(self.disconnect) self.ui.actionExit.triggered.connect(QtGui.qApp.quit) self.ui.comPort.currentIndexChanged.connect(self.updateDetectedPorts) self.ui.actionBootUpDelay.triggered.connect(self.updateBootUpDelay) self.ui.actionCommTimeout.triggered.connect(self.updateCommTimeOut) '''Communication Methods''' def connect(self): '''Initiates communication with the AeroQuad''' # Setup GUI self.ui.status.setText("Connecting to the " + self.selectedBoardType + "...") self.ui.buttonDisconnect.setEnabled(True) self.ui.buttonConnect.setEnabled(False) self.ui.comPort.setEnabled(False) self.ui.baudRate.setEnabled(False) # Update the GUI app.processEvents() # Setup serial port bootupDelay = float(xml.find("./Settings/BootUpDelay").text) commTimeOut = float(xml.find("./Settings/CommTimeOut").text) self.comm.connect(str(self.ui.comPort.currentText()), int(self.ui.baudRate.currentText()), bootupDelay, commTimeOut) self.comm.write("!") version = self.comm.read() if version != "": self.storeComPortSelection() self.ui.status.setText("Connected to the " + self.selectedBoardType + " using Flight Software v" + version) self.restartSubPanel() else: self.disconnect() self.ui.status.setText("Not connected to the " + self.selectedBoardType) def disconnect(self): '''Disconnect from the AeroQuad''' self.comm.write("X") self.comm.disconnect() # Update GUI self.ui.buttonDisconnect.setEnabled(False) self.ui.buttonConnect.setEnabled(True) self.ui.comPort.setEnabled(True) self.ui.baudRate.setEnabled(True) self.ui.status.setText("Disconnected from the " + self.selectedBoardType) self.restartSubPanel() def updateDetectedPorts(self): '''Cycles through 256 ports and checks if there is a response from them.''' selection = self.ui.comPort.currentText() if selection == "Refresh": self.updateComPortSelection self.ui.comPort.setCurrentIndex(0) self.ui.status.setText("Updated list of available COM ports") elif selection == "Autoconnect": self.ui.comPort.setCurrentIndex(0) self.ui.status.setText("This feature still under construction") elif selection == "-------": self.ui.comPort.setCurrentIndex(0) def updateBootUpDelay(self): '''Creates dialog box to ask user for desired boot up delay. This delay waits for Arduino based boards to finish booting up before sending commands. ''' bootUpDelay = float(xml.find("./Settings/BootUpDelay").text) data, ok = QtGui.QInputDialog.getDouble(self, "Boot Up Delay", "Boot Up Delay:", bootUpDelay, 0, 60, 3) if ok: xml.find("./Settings/BootUpDelay").text = str(data) xml.write("AeroQuadConfigurator.xml") def updateCommTimeOut(self): '''Creates dialog box to ask user for desired comm timeout. This is timeout value used by serial drivers to wait for response from device ''' commTimeOut = float(xml.find("./Settings/CommTimeOut").text) data, ok = QtGui.QInputDialog.getDouble(self, "Comm Time Out", "Comm Time Out:", commTimeOut, 0, 60, 3) if ok: xml.find("./Settings/CommTimeOut").text = str(data) xml.write("AeroQuadConfigurator.xml") def updateComPortSelection(self): '''Look for available comm ports and updates combo box''' self.ui.comPort.clear() for n in self.comm.detectPorts(): self.ui.comPort.addItem(n) self.ui.comPort.addItem("-------") self.ui.comPort.addItem("Autoconnect") self.ui.comPort.addItem("Refresh") def storeComPortSelection(self): '''Stores comm port selection to xml file for later recall''' xml.find("./Settings/DefaultBaudRate").text = str(self.ui.baudRate.currentText()) xml.find("./Settings/DefaultComPort").text = str(self.ui.comPort.currentText()) xml.write("AeroQuadConfigurator.xml") def updateBaudRates(self): '''Reads baud rates from xml and displays in combo box. Updates the xml file to display different baud rates ''' defaultBaudRate = xml.find("./Settings/DefaultBaudRate").text baudRates = xml.find("./Settings/AvailableBaudRates").text baudRate = baudRates.split(',') for i in baudRate: self.ui.baudRate.addItem(i) self.ui.baudRate.setCurrentIndex(baudRate.index(defaultBaudRate)) '''Board Selection Methods''' def configureBoardTypeMenu(self): '''Dynamically add board types to menu bar''' boardNames = xml.findall("./Boards/Type") self.boardTypes = [] self.boardMenu = [] for board in boardNames: self.boardTypes.append(board.text) self.boardTypeMapper = QtCore.QSignalMapper(self) for boardType in self.boardTypes: self.ui.board = self.ui.menuBoard.addAction(boardType) self.boardMenu.append(self.ui.board) # Need to store this separately because Python only binds stuff at runtime self.boardTypeMapper.setMapping(self.ui.board, boardType) self.ui.board.triggered.connect(self.boardTypeMapper.map) self.ui.board.setCheckable(True) self.boardTypeMapper.mapped[str].connect(self.selectBoardType) selectedBoardType = xml.find("./Boards/Selected").text self.checkmarkBoardType(selectedBoardType) return selectedBoardType def selectBoardType(self, boardType): '''Places check mark beside selected board type Menu item instances stored in dedicated list because Python only updates during runtime making everything point to the last item in the list ''' types = len(self.boardTypes) for name in range(types): self.boardMenu[name].setChecked(False) self.checkmarkBoardType(boardType) selected = self.boardTypes.index(boardType) self.boardMenu[selected].setChecked(True) xml.find("./Boards/Selected").text = str(boardType) xml.write("AeroQuadConfigurator.xml") self.selectedBoardType = boardType self.clearSubPanelMenu() self.configureSubPanelMenu(boardType) self.ui.subPanel.setCurrentIndex(0) def checkmarkBoardType(self, boardType): '''Place checkmark next to selected board type''' selected = self.boardTypes.index(boardType) self.boardMenu[selected].setChecked(True) ''' SubPanel Methods ''' def configureSubPanelMenu(self, boardType): '''Dynamically add subpanels to View menu based on selected board type''' boardSubPanelName = "./Board/[@Type='" + str(boardType) + "']/Subpanels/Subpanel" subPanels = xml.findall(boardSubPanelName) subPanelCount = 1 self.subPanelList = [] self.subPanelClasses = [] for subPanel in subPanels: self.subPanelList.append(subPanel.get("Name")) pathName = xml.find(boardSubPanelName + "/[@Name='" + subPanel.get("Name") +"']/Path").text className = xml.find(boardSubPanelName + "/[@Name='" + subPanel.get("Name") +"']/Class").text packageList = pathName.split('.') packageString = packageList[0] + '.' + packageList[1] module = __import__(packageString) for package in packageList[1:]: module = getattr(module, package) module = getattr(module, className) tempSubPanel = module() tempSubPanel.setupUi(tempSubPanel, self.comm) self.ui.subPanel.addWidget(tempSubPanel) self.subPanelClasses.append(tempSubPanel) subPanelCount += 1 self.subPanelMapper = QtCore.QSignalMapper(self) self.subPanelMenu = [] for subPanelName in self.subPanelList: subPanel = self.ui.menuView.addAction(subPanelName) self.subPanelMenu.append(subPanel) # Need to store this separately because Python only binds stuff at runtime self.subPanelMapper.setMapping(subPanel, subPanelName) subPanel.triggered.connect(self.subPanelMapper.map) subPanel.setCheckable(True) self.subPanelMapper.mapped[str].connect(self.selectSubPanel) def selectSubPanel(self, subPanelName): '''Places check mark beside selected subpanel name Menu item instances stored in dedicated list because Python only updates during runtime making everything point to the last item in the list ''' if self.activeSubPanel != None: self.activeSubPanel.stop() types = len(self.subPanelList) for index in range(types): self.subPanelMenu[index].setChecked(False) selected = self.subPanelList.index(subPanelName) self.subPanelMenu[selected].setChecked(True) self.ui.subPanel.setCurrentIndex(selected+1) # index 0 is splash screen self.activeSubPanel = self.subPanelClasses[selected] self.activeSubPanel.start() def clearSubPanelMenu(self): ''' Clear subPanel menu and disconnect subPanel related signals''' self.ui.menuView.clear() self.subPanelMapper.mapped[str].disconnect(self.selectSubPanel) def restartSubPanel(self): if self.activeSubPanel != None: # Restart any running subpanels self.activeSubPanel.stop() self.activeSubPanel.start() ''' Housekeeping Functions''' def exit(self): self.comm.disconnect() sys.exit(app.exec_())
class CMainWindow(QMainWindow): def __init__(self, *args): self.ser = None self.reader = CReader() self.writer = CWriter() apply(QMainWindow.__init__, (self, ) + args) self.ui = Ui_MainWindow() self.setupUi() self.printInfo("Ready...") def setupUi(self): self.ui.setupUi(self) self.ui.baudRateComboBox.addItems(baudRates) self.refreshPorts() QObject.connect(self.ui.exitPushButton, SIGNAL("clicked()"), self, SLOT("close()")) QObject.connect(self.ui.refreshPortsPushButton, SIGNAL("clicked()"), self.refreshPorts) QObject.connect(self.ui.connectPushButton, SIGNAL("clicked()"), self.connect) QObject.connect(self.ui.disconnectPushButton, SIGNAL("clicked()"), self.disconnect) QObject.connect(self.ui.cmdLineEdit, SIGNAL("returnPressed()"), self.processCmd) QObject.connect(self.reader, SIGNAL("newData(QString)"), self.updateLog) QObject.connect(self.reader, SIGNAL("error(QString)"), self.printError) QObject.connect(self.writer, SIGNAL("error(QString)"), self.printError) def getUSBPorts(self): return glob.glob("/dev/ttyUSB*") def getSPPorts(self): return glob.glob("/dev/ttyS*") def getSelectedPort(self): return self.ui.portsComboBox.currentText() def getSelectedBaudRate(self): return self.ui.baudRateComboBox.currentText() def refreshPorts(self): self.ui.portsComboBox.clear() self.ui.portsComboBox.addItems(sorted(self.getUSBPorts())) self.ui.portsComboBox.addItems(sorted(self.getSPPorts())) def connect(self): self.disconnect() try: self.printInfo("Connecting to %s with %s baud rate." % \ (self.getSelectedPort(), self.getSelectedBaudRate())) self.ser = serial.Serial(str(self.getSelectedPort()), \ int(self.getSelectedBaudRate())) self.startReader(self.ser) self.printInfo("Connected successfully.") except: self.ser = None self.printError("Failed to connect!") def disconnect(self): self.stopThreads() if self.ser == None: return try: if self.ser.isOpen: self.ser.close() self.printInfo("Disconnected successfully.") except: self.printError("Failed to disconnect!") self.ser = None def startReader(self, ser): self.reader.start(ser) def stopThreads(self): self.stopReader() self.stopWriter() def stopReader(self): if self.reader.isRunning(): self.reader.terminate() def stopWriter(self): if self.writer.isRunning(): self.writer.terminate() def printInfo(self, text): self.ui.logPlainTextEdit.appendPlainText(text) self.ui.logPlainTextEdit.moveCursor(QTextCursor.End) def printError(self, text): self.ui.logPlainTextEdit.appendPlainText(text) self.ui.logPlainTextEdit.moveCursor(QTextCursor.End) def printCmd(self, text): self.ui.logPlainTextEdit.appendPlainText("> " + text + "\n\n") self.ui.logPlainTextEdit.moveCursor(QTextCursor.End) def updateLog(self, text): self.ui.logPlainTextEdit.moveCursor(QTextCursor.End) self.ui.logPlainTextEdit.insertPlainText(text) self.ui.logPlainTextEdit.moveCursor(QTextCursor.End) def processCmd(self): cmd = self.ui.cmdLineEdit.text() self.printCmd(cmd) self.writer.start(self.ser, cmd) self.ui.cmdLineEdit.clear() def closeEvent(self, event): self.disconnect()
class MyWindow(QtWidgets.QMainWindow, Ui_MainWindow): def __init__(self): QtWidgets.QMainWindow.__init__(self) Ui_MainWindow.__init__(self) # Set MyWindow to the center of the desktop qtRectangle = self.frameGeometry() centerPoint = QDesktopWidget().availableGeometry().center() qtRectangle.moveCenter(centerPoint) self.move(qtRectangle.topLeft()) # set other functions self.ui = Ui_MainWindow() self.ui.setupUi(self) #self.ui.action_Open1.clicked.connect(self.browseFile1) #self.ui.action_Open2.clicked.connect(self.browseFile2) self.ui.btnBrowse1.clicked.connect(self.browseFile1) self.ui.btnBrowse2.clicked.connect(self.browseFile2) #self.ui.action_Close.clicked.connect(self.closeFiles) self.ui.btnExit.clicked.connect(self.exitApp) self.ui.btnProcess.clicked.connect(self.doProcess) self.ui.btnAbout.clicked.connect(self.openAbout) # Close all files def closeFiles(self): self.ui.txLog.appendPlainText('Close all files.') # Browse for files def browseFile1(self): self.ui.txLog.appendPlainText('Browse file 1.') options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog fileName, _ = QFileDialog.getOpenFileName(self, "QFileDialog.getOpenFileName()", "","All Files (*);;Excel files (*.xlsx)", options=options) if fileName: self.ui.txFile1.setText(fileName) self.ui.txLog.appendPlainText('File 1: ' + fileName + ' has been selected.') def browseFile2(self): self.ui.txLog.appendPlainText('Browse file 2.') options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog fileName, _ = QFileDialog.getOpenFileName(self, "QFileDialog.getOpenFileName()", "","All Files (*);;Excel files (*.xlsx)", options=options) if fileName: self.ui.txFile2.setText(fileName) self.ui.txLog.appendPlainText('File 2: ' + fileName + ' has been selected.') # Process the files def doProcess(self): self.ui.txLog.appendPlainText('Processing all files.') # Exit application def exitApp(self): self.ui.txLog.appendPlainText('Exit application.') sys.exit() # Open form About def openAbout(self): frAbout = FrAbout() frAbout.show()
class AppWindow(QMainWindow): def __init__(self): super().__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setCallback() self.currentRadarConfig # self.benchMarkDistance = 0 #distance between marks self.figureBScan = plt.figure() self.canvasBScan = FigureCanvas(self.figureBScan) self.ui.BScanImage.addWidget(self.canvasBScan) self.axBScan = self.figureBScan.add_subplot(111) self.canvasBScan.draw() self.figureCoordinate = plt.figure() self.canvesCoordinate = FigureCanvas(self.figureCoordinate) self.ui.RangeNetPlot.addWidget(self.canvesCoordinate) self.axCoordinate = self.figureCoordinate.add_subplot(111) self.canvesCoordinate.draw() plt.tight_layout() timer = QtCore.QTimer(self) timer.timeout.connect(self.updateCanvas) timer.start(50) self.producer = ProducerThread().start() def setCallback(self): self.ui.btnRadarConfigRead.clicked.connect(self.readConfig) self.ui.btnRadarConfigSet.clicked.connect(self.writeConfig) self.ui.btnStart.clicked.connect(self.runAndStop) self.ui.btnSave.clicked.connect(self.saveData) self.ui.btnClear.clicked.connect(self.clearWindow) self.ui.btnNodeIdSet.clicked.connect(self.setRangeNode) def readConfig(self): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect((ip, port)) requestConfigMsg = struct.pack('>HH', 0x1002, 0) s.sendto(requestConfigMsg, ipAddress) configMessage, addr = s.recvfrom(44) self.currentRadarConfig = config.RadarConfig(configMessage) self.ui.editIntegratinoIdex.setText( str(self.currentRadarConfig.baseIntegrationIndex)) self.ui.editTransmitGain.setText( str(self.currentRadarConfig.transmitGain)) self.ui.editDistanceEnd.setText( str(config.ps2m(self.currentRadarConfig.scanEnd))) self.ui.editDistanceStart.setText( str(config.ps2m(self.currentRadarConfig.scanStart))) #set ui def writeConfig(self): T1, T2 = config.m2ps(float(self.ui.editDistanceStart.text()), float(self.ui.editDistanceEnd.text())) self.currentRadarConfig.scanStart = T1 self.currentRadarConfig.scanEnd = T2 self.currentRadarConfig.transmitGain = int( self.ui.editTransmitGain.text()) self.currentRadarConfig.baseIntegrationIndex = int( self.ui.editIntegratinoIdex.text()) s.socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.sendto(self.currentRadarConfig.configToByte(), ipAddress) msgWriteConfirm, add = s.recvfrom(20) msgType, msgId, msgStatus = unpack('>HHI', msgWriteConfirm) if msgType == 0x1101 and msgStatus == 0: self.showMessage('write success !') else: self.showMessage('faild !') pass #set node id def setRangeNode(self): nodeIdA = int(self.ui.editNodeIDInputA.text()) nodeIdB = int(self.ui.editNodeIDInputB.text()) benchMarkDistance = int(self.ui.editDistance.text()) self.ui.labelDistance.setText(str(benchMarkDistance)) self.ui.labelNodeA.setText(str(nodeIdA)) self.ui.labelNodeB.setText(str(nodeIdB)) def updateCanvas(self): if not updateFigureFlag: return global queue if queue: lock.acquire for line in queue: self.dataOriginal.add(line[2:]) self.axBScan.clear() lastFrame = self.dataOriginal.getLastFrame(windowLength + 1) envelop = np.abs(hilbert(lastFrame[0:-1] - lastFrame[1:])) envelop = np.clip(np.round(63 * envelop / 10e3) + 1, -1e5, 64) self.axBScan.imshow(envelop, aspect='auto') self.canvasBScan.draw() queue = [] lock.release() # draw range plot xCoordinate = (rangeA**2 + self.benchMarkDistance**2 - rangeB**2) / (2 * self.benchMarkDistance) yCoordinate = math.sqrt(rangeA**2 - self.benchMarkDistance**2) x = [0, self.benchMarkDistance, xCoordinate] y = [0, 0, yCoordinate] self.axCoordinate.scatter(x, y) self.canvesCoordinate.draw() def clearWindow(self): self.dataOriginal = signalArray.SignalArray() self.updateCanvas() def saveData(self): fileName = str(datetime.datetime.now())[0:19].replace(' ', '_')\ .replace('-', '_').replace(':', '_').replace('.', '_') np.savetxt(fileName, self.dataOriginal.getAllArrays()) self.showMessage(fileName + ' is saved !') def showMessage(self, text): msg = QMessageBox() msg.setText(text) msg.setStandardButtons(QMessageBox.Ok) ret = msg.exec_() def runAndStop(self): global threadRunningFlag global updateFigureFlag if threadRunningFlag: threadRunningFlag = False updateFigureFlag = False self.ui.btnStart.setText('Start') else: self.dataOriginal = signalArray.SignalArray() self.dataProcessed = [] threadRunningFlag = True updateFigureFlag = True self.ui.btnStart.setText('End')
class SeptimoArte(QtGui.QWidget): """Clase principal de programa.""" columnas_actor = ( (u"Nombre", 200), (u"Cumpleaños", 100), (u"Genero", 100), (u"N° Películas", 50)) def __init__(self): """Constructor principal.""" super(SeptimoArte, self).__init__() self.tipoModel = None self.ui = Ui_MainWindow() self.ui.setupUi(self) self.centerWindow() self.setModel() #self.loadMovies() self.setSignals() self.show() def centerWindow(self): """ Funcion que centra la interfaz grafica en la pantalla del usuario. """ qr = self.frameGeometry() cp = QtGui.QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) def setModel(self): """ Define el módelo de la grilla para trabajarla. """ self.proxyModel = QtGui.QSortFilterProxyModel() self.proxyModel.setDynamicSortFilter(True) self.ui.actoresTreeView.sortByColumn(0, QtCore.Qt.AscendingOrder) self.ui.actoresTreeView.setModel(self.proxyModel) def setSourceModel(self, model): """ Actualiza constantemente el origen de los datos para siempre tenerlos al día así pudiendo buscar y mostrar solo algunos datos. """ self.proxyModel.setSourceModel(model) def loadTableData(self, parent): """ Llama a los métodos respectivos para llenar ambas grillas en la app. """ self.tipoModel = parent model = self.loadActors(parent) return model #*********************************************************************** # Estructuración del tab Actores #*********************************************************************** def loadActors(self, parent): self.comboBoxTabActor() actores = controller.actor() row = len(actores) model = QtGui.QStandardItemModel(row, len(self.columnas_actor), parent) for col, h in enumerate(self.columnas_actor): model.setHeaderData(col, QtCore.Qt.Horizontal, h[0]) self.ui.actoresTreeView.setColumnWidth(col, h[1]) for i, data in enumerate(actores): row = [data[1], data[2], data[3]] for j, field in enumerate(row): index = model.index(i, j, QtCore.QModelIndex()) model.setData(index, field) return model def comboBoxTabActor(self): """ Rellena el comboBox que se ubica en el Tab Actor (principal) con todas las películas que se encuentran en la base de datos para luego utilizarlas para filtrar el contenido de la grilla. """ peliculas = controller.pelicula() self.ui.buscarAPeliculaComboBox.insertItem(0, u"Todas") for i, data in enumerate(peliculas): self.ui.buscarAPeliculaComboBox.insertItem(i + 1, data[1]) def setSignals(self): self.ui.actoresTreeView.clicked.connect(self.infoClick) self.ui.actoresTreeView.activated.connect(self.infoClick) self.ui.buscarANombreLineEdit.textChanged.connect( self.filtrarActorNombre) self.ui.buscarAPeliculaComboBox.currentIndexChanged.connect( self.filtrarActorPelicula) self.ui.nuevoAButton.clicked.connect(self.nuevoActor) def infoClick(self): indexTab = self.ui.tabWidget.currentIndex() index = self.ui.actoresTreeView.currentIndex() # n° fila tabla model = self.ui.actoresTreeView.model() if indexTab is 0: #Estamos en el tab Actores nombre = model.index(index.row(), 0, QtCore.QModelIndex()).data() a = controller.obtenerActor(nombre) direccion = "imgActor/{0}".format(a.imagen) self.ui.actorImagenLabel.setPixmap(QtGui.QPixmap(direccion)) else: #Estamos en el tab Películas pass def filtrarActorNombre(self): self.ui.actorImagenLabel.setPixmap(QtGui.QPixmap("")) # Oculta la img self.proxyModel.setFilterKeyColumn(0) regExp = QtCore.QRegExp(self.ui.buscarANombreLineEdit.text(), QtCore.Qt.CaseInsensitive, QtCore.QRegExp.RegExp) self.proxyModel.setFilterRegExp(regExp) def filtrarActorPelicula(self, parent): self.ui.actorImagenLabel.setPixmap(QtGui.QPixmap("")) index = self.ui.buscarAPeliculaComboBox.currentIndex() if (index != 0): nombre = self.ui.buscarAPeliculaComboBox.itemText(index) pelicula = controller.obtenerPelicula(nombre) # Info de la pelicula actores = controller.actoresDePelicula(pelicula.id_pelicula) actoresAFiltrar = "" for i, data in enumerate(actores): row = data[0] if i == len(actores) - 1: actoresAFiltrar += row[1] else: actoresAFiltrar += row[1] + "|" if actoresAFiltrar is "": actoresAFiltrar = u"@" else: self.proxyModel.setFilterKeyColumn(0) actoresAFiltrar = u'|' actoresFiltrados = QtCore.QRegExp( actoresAFiltrar, QtCore.Qt.CaseInsensitive, QtCore.QRegExp.RegExp) self.proxyModel.setFilterRegExp(actoresFiltrados) def nuevoActor(self): form = FormularioPelicula() form.exec_() self.setSourceModel(self.loadTableData(self.tipoModel))
class mywindow(QtWidgets.QMainWindow): resized = QtCore.pyqtSignal() def __init__(self, parent = None): super(mywindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.img_path = None self._img_original = None self._img_preview = None self.ALL = [0 for i in range(256)] self.RED = [0 for i in range(256)] self.GREEN = [0 for i in range(256)] self.BLUE = [0 for i in range(256)] self.ui.editorWidget.setVisible(False) self.reset_sliders() self.resized.connect(self.someFunction) self.ui.reset_btn.setEnabled(False) self.ui.saveBtn.setEnabled(False) self.ui.uploadBtn.clicked.connect(self.upload_img) self.ui.reset_btn.clicked.connect(self.reset) self.ui.saveBtn.clicked.connect(self.save_img) self.ui.brightness_sld.valueChanged.connect(self.Change) self.ui.contrast_sld.valueChanged.connect(self.Change) self.ui.red_sld.valueChanged.connect(self.Change) self.ui.green_sld.valueChanged.connect(self.Change) self.ui.blue_sld.valueChanged.connect(self.Change) def resizeEvent(self, event): self.resized.emit() return super(mywindow, self).resizeEvent(event) def someFunction(self): if (self._img_preview): pix = QPixmap.fromImage(self._img_preview) my_pix = pix.copy() ratio = my_pix.width()/my_pix.height() if (ratio <= 1): height = self.ui.imgLabel.height() width = height / ratio else: width = self.ui.imgLabel.width() height = width / ratio my_pix = my_pix.scaled(width, height, Qt.KeepAspectRatio) self.ui.imgLabel.setPixmap(my_pix) def save_img(self): logger.debug("open save dialog") new_img_path, _ = QFileDialog.getSaveFileName(self, "Save File", "", "Images (*.png *.xpm *.jpg)") if new_img_path: logger.debug(f"save output image to {new_img_path}") img = QPixmap.fromImage(self._img_preview) width = int(self.ui.width_edit.text()) height = int(self.ui.height_edit.text()) my_pix = img.scaled(width, height, Qt.KeepAspectRatio) my_pix.save(new_img_path, "PNG") def reset(self): self.reset_sliders() if self._img_original is not None: self.ui.width_edit.setText(str(self._img_original.width())) self.ui.height_edit.setText(str(self._img_original.height())) def reset_sliders(self): self.ui.contrast_sld.setValue(0) self.ui.brightness_sld.setValue(0) self.ui.blue_sld.setValue(0) self.ui.red_sld.setValue(0) self.ui.green_sld.setValue(0) def upload_img (self): logger.debug("upload") #Загружаем изображение self.img_path, _ = QFileDialog.getOpenFileName(self, "Open Image", "/Users", "Image Files (*.png *.jpg *.bmp)") if self.img_path: self.reset() self.ui.editorWidget.setVisible(True) self.ui.reset_btn.setEnabled(True) self.ui.saveBtn.setEnabled(True) #Храним изображение pix = QPixmap(self.img_path).toImage() self._img_original = pix self._img_preview = pix self.ui.width_edit.setText(str(self._img_original.width())) self.ui.height_edit.setText(str(self._img_original.height())) #Рисуем гистограмму self.drawGist() #####################pix.save("somefile.png", "PNG") ###################pix.setPixel(0,0,qRgb(0,0,0)) #####print(pix.width()) my_pix = pix.copy() print(my_pix.width(), my_pix.height()) ratio = my_pix.width()/my_pix.height() if (ratio <= 1): height = self.ui.imgLabel.height() width = height / ratio else: width = self.ui.imgLabel.width() height = width / ratio my_pix = QPixmap.fromImage(my_pix) my_pix = my_pix.scaled(width, height, Qt.KeepAspectRatio) self.ui.imgLabel.setPixmap(my_pix) #self.ui.imgLabel.setScaledContents(True) #Функция для рисования гистограмм def drawGist(self): self.ui.red_gist.clear() self.ui.all_gist.clear() self.ui.blue_gist.clear() self.ui.green_gist.clear() self.ALL = [0 for i in range(256)] self.RED = [0 for i in range(256)] self.GREEN = [0 for i in range(256)] self.BLUE = [0 for i in range(256)] (width, height) = (self._img_preview.width(), self._img_preview.height()) rgb_img = self._img_preview for i in range(width): for j in range(height): cc = QColor(rgb_img.pixel(i,j)) R, G, B = (cc.red(), cc.green(), cc.blue()) A = int(0.3 * R + 0.59 * G + 0.11 * B) self.GREEN[G] += 1 self.BLUE[B] += 1 self.RED[R] += 1 self.ALL[A] += 1 #Строим гистограмму self.ui.green_gist.plot(self.GREEN, pen=(0,255,0)) self.ui.red_gist.plot(self.RED, pen=(255,0,0)) self.ui.blue_gist.plot(self.BLUE, pen=(0,0,255)) self.ui.all_gist.plot(self.ALL, brush=(50,50,200,100)) def get_edit_image(self): self._img_preview = self._img_original.copy() if (self.ui.brightness_sld.value() != 0): self.changeBrightness(self.ui.brightness_sld.value()) if (self.ui.contrast_sld.value() != 0): self.changeContrast(self.ui.contrast_sld.value()) if (self.ui.red_sld.value() != 0): self.changeRGB(self.ui.red_sld.value(),0) if (self.ui.green_sld.value() != 0): self.changeRGB(self.ui.green_sld.value(),1) if (self.ui.blue_sld.value() != 0): self.changeRGB(self.ui.blue_sld.value(),2) pix = QPixmap.fromImage(self._img_preview) self.drawGist() my_pix = pix.copy() print(my_pix.width(), my_pix.height()) ratio = my_pix.width()/my_pix.height() if (ratio <= 1): height = self.ui.imgLabel.height() width = height / ratio else: width = self.ui.imgLabel.width() height = width / ratio #my_pix = QPixmap.fromImage(my_pix) my_pix = my_pix.scaled(width, height, Qt.KeepAspectRatio) self.ui.imgLabel.setPixmap(my_pix) def changeBrightness(self, value): (width, height) = (self._img_preview.width(), self._img_preview.height()) N = value for i in range(width): for j in range(height): cc = QColor(self._img_preview.pixel(i,j)) R, G, B = (self.getbyte(cc.red() + (N * 128)/100), self.getbyte(cc.green() + (N * 128)/100 ), self.getbyte(cc.blue() + (N * 128)/100)) self._img_preview.setPixel(i,j, qRgb(R,G,B)) #pix[i,j] = (self.getbyte(pix[i,j][0] + value), self.getbyte(pix[i,j][1] + value), self.getbyte(pix[i,j][2] + value)) def changeContrast(self, value): (width, height) = (self._img_preview.width(), self._img_preview.height()) N = value for i in range(width): for j in range(height): cc = QColor(self._img_preview.pixel(i,j)) if (N > 0): R, G, B = (self.getbyte((cc.red() * (100 - N) - 128 * N)/(100)), self.getbyte((cc.green() * (100 - N) - 128 * N)/(100)), self.getbyte((cc.blue() * (100 - N) - 128 * N)/(100))) else: R, G, B = (self.getbyte((cc.red() * 100 - 128 * N)/(100 - N)), self.getbyte((cc.green() * 100 - 128 * N)/(100 - N)), self.getbyte((cc.blue() * 100 - 128 * N)/(100 - N))) self._img_preview.setPixel(i,j, qRgb(R,G,B)) #pix[i,j] = (self.getbyte(pix[i,j][0] + value), self.getbyte(pix[i,j][1] + value), self.getbyte(pix[i,j][2] + value)) def changeRGB(self, value, imt): (width, height) = (self._img_preview.width(), self._img_preview.height()) N = value for i in range(width): for j in range(height): cc = QColor(self._img_preview.pixel(i,j)) if (imt == 0): R, G, B = (self.getbyte((cc.red() + (N * 128)/100)), cc.green(), cc.blue()) elif (imt == 1): R, G, B = (cc.red(), self.getbyte((cc.green() + (N * 128)/100)), cc.blue()) else: R, G, B = (cc.red(), cc.green(), self.getbyte((cc.blue() + (N * 128)/100))) self._img_preview.setPixel(i,j, qRgb(R,G,B)) #pix[i,j] = (self.getbyte(pix[i,j][0] + value), self.getbyte(pix[i,j][1] + value), self.getbyte(pix[i,j][2] + value)) def Change(self, value): self.get_edit_image() def getbyte(self, i): if (i > 255): return 255 if (i < 0): return 0 return int(i)
class Main(QtGui.QMainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.btnConvert.clicked.connect(self.btnConvert_clicked) self.ui.btnDefault.clicked.connect(self.btnDefault_clicked) def btnConvert_clicked(self): src_txt = unicode (self.ui.te_src.toPlainText().toUtf8(), "utf-8") opt_txt = unicode (self.ui.te_opt.toPlainText().toUtf8(), "utf-8") from_val = self.ui.cb_src.currentIndex() to_val = self.ui.cb_opt.currentIndex() usc = UgScriptConverter() # 0 Uyghur, 1 Latin, 2 Common Turkish if from_val == to_val: opt_txt = src_txt elif from_val == 0: if to_val == 1: # Uyghur to Latin opt_txt = usc.UA2LT(src_txt) elif to_val == 2: # Uyghur to Common Turkish opt_txt = usc.UA2CT(src_txt) elif from_val == 1: if to_val == 0: # Latin to Uyghur opt_txt = usc.LA2UA(src_txt) elif to_val == 2: # Latin to Common Turkish opt_txt = usc.LA2CT(src_txt) elif from_val == 2: if to_val == 0: # Common Turkish to Uyghur opt_txt = usc.CT2UA(src_txt) elif to_val == 1: # Common Turkish to Latin opt_txt = usc.CT2LA(src_txt) self.ui.te_opt.setText(opt_txt) # print from_val # print to_val # text = u"ھەممە ئادەم تۇغۇلۇشىدىنلا ئەركىن، ئىززەت-ھۆرمەت ۋە ھوقۇقتا باب-باراۋەر بولۇپ تۇغۇلغان."+\ # u' ئۇلار ئەقىلگە ۋە ۋىجدانغا ئىگە ھەمدە بىر-بىرىگە قېرىنداشلىق مۇناسىۋىتىگە'+\ # u" خاس روھ بىلەن مۇئامىلە قىلىشى كېرەك." # latin_text = u"Hemme adem tughulushidinla erkin, izzet-hörmet we hoquqta bab-barawer "+\ # u"bolup tughulghan. Ular eqilge we wijdan'gha ige hemde bir-birige qérindashliq munasiwitige "+\ # u"xas roh bilen muamile qilishi kérek." # ct_text = u"Hemme adem tuğuluşidinla erkin, izzet-hörmet ve hoquqta bab-baraver bolup tuğulğan."+\ # u" Ular eqilge ve vijdanğa ige hemde bir-birige qérindaşliq munasivitige xas roh bilen mu'amile qilişi kérek. ? <<>>" # # latin_text = "adem adem" # self.ui.te_src.setText(ct_text) # usc = UgScriptConverter() # # ug_text = usc.CT2UA(ct_text) # # self.ui.textEdit_2.setText(ug_text) # # sys.exit() # ug_text = usc.LA2UA(latin_text) # self.ui.te_opt.setText(ug_text) # ct_text= usc.LA2CT(latin_text) # self.ui.te_opt.setText(ct_text) def btnDefault_clicked(self): ug_text = u"چەتئەل" from_val = self.ui.cb_src.currentIndex() if from_val == 0: self.ui.te_src.setText(ug_text) elif from_val == 1: pass elif from_val == 1: pass elif from_val == 1: pass elif from_val == 1: pass else: pass
class mainWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): QtWidgets.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) setVerbosity("debug") #Button actions self.ui.pushButton_en_server.clicked.connect(self.pushButton_serverEnable_onClicked) self.ui.pushButton_en_client.clicked.connect(self.pushButton_clientEnable_onClicked) self.ui.pushButton_chart_orientation.clicked.connect(self.pushButton_chartOrientation_onClicked) self.ui.pushButton_3d_model.clicked.connect(self.pushButton_3D_Model_onClicked) self.ui.pushButton_angle_set.clicked.connect(self.pushButton_angleSetPID_onClicked) self.ui.pushButton_speed_set.clicked.connect(self.pushButton_speedSetPID_onClicked) self.ui.pushButton_angle_zero.clicked.connect(self.pushButton_angleZeroPID_onClicked) self.ui.pushButton_speed_zero.clicked.connect(self.pushButton_speedZeroPID_onClicked) self.ui.pushButton_control_set.clicked.connect(self.pushButton_controlSet_onClicked) #Initial value self.ui.doubleSpinBox_angle_kp.setValue(ANGLE_KP_CONS) self.ui.doubleSpinBox_angle_ki.setValue(ANGLE_KI_CONS) self.ui.doubleSpinBox_angle_kd.setValue(ANGLE_KD_CONS) self.ui.doubleSpinBox_angle_kp_Aggr.setValue(ANGLE_KP_AGGR) self.ui.doubleSpinBox_angle_ki_Aggr.setValue(ANGLE_KI_AGGR) self.ui.doubleSpinBox_angle_kd_Aggr.setValue(ANGLE_KD_AGGR) self.ui.doubleSpinBox_angle_setpoint.setValue(CALIBRATED_ZERO_ANGLE) self.ui.doubleSpinBox_angle_max.setValue(ANGLE_LIMIT) self.ui.doubleSpinBox_speed_kp.setValue(SPEED_KP) self.ui.doubleSpinBox_speed_ki.setValue(SPEED_KI) self.ui.doubleSpinBox_speed_kd.setValue(SPEED_KD) self.serverUDPQueue = queue.Queue(4) self.threads = [] self.worker = None self.clientUDP = None self.serverUDP = None def pushButton_serverEnable_onClicked(self): #Create and start UDP server thread port = int(self.ui.lineEdit_port_server.text()) if self.serverUDP != None and self.worker != None: self.worker.terminate() self.serverUDP.join(timeout=1) self.worker = Worker(self) self.serverUDP = UDP_ServerThread(name=SERVER_UDP_NAME, queue=self.serverUDPQueue, UDP_PORT=port) self.serverUDP.daemon = True self.threads.append(self.serverUDP) self.serverUDP.start() self.worker.start() def pushButton_clientEnable_onClicked(self): #Create and start UDP client thread ip = self.ui.lineEdit_ip_client.text() port = int(self.ui.lineEdit_port_client.text()) if self.clientUDP != None: self.clientUDP.join(timeout=1) self.clientUDP = UDP_ClientThread(name=CLIENT_UDP_NAME, UDP_IP=ip, UDP_PORT=port) self.clientUDP.daemon = True self.threads.append(self.clientUDP) self.clientUDP.start() def pushButton_chartOrientation_onClicked(self): self.plot = Plot(self) self.plot.start() def pushButton_3D_Model_onClicked(self): self.triModel = TriModel(self) self.triModel.start() def pushButton_angleSetPID_onClicked(self): angleKpCons = self.ui.doubleSpinBox_angle_kp.value() angleKiCons = self.ui.doubleSpinBox_angle_ki.value() angleKdCons = self.ui.doubleSpinBox_angle_kd.value() angleKpAggr = self.ui.doubleSpinBox_angle_kp_Aggr.value() angleKiAggr = self.ui.doubleSpinBox_angle_ki_Aggr.value() angleKdAggr = self.ui.doubleSpinBox_angle_kd_Aggr.value() angleSetpoint = self.ui.doubleSpinBox_angle_setpoint.value() angleMax = self.ui.doubleSpinBox_angle_max.value() #(module),(data1)(data2),(data3)(...)(#) msg = CMD_PID_ANGLE + "," + \ str(angleKpCons) + "," + \ str(angleKiCons) + "," + \ str(angleKdCons) + "," + \ str(angleKpAggr) + "," + \ str(angleKiAggr) + "," + \ str(angleKdAggr) + "," + \ str(angleSetpoint) + "," + \ str(angleMax) + "#" # Sending UDP packets... if (self.clientUDP != None): self.clientUDP.putMessage(msg) def pushButton_speedSetPID_onClicked(self): speedKpCons = self.ui.doubleSpinBox_speed_kp.value() speedKiCons = self.ui.doubleSpinBox_speed_ki.value() speedKdCons = self.ui.doubleSpinBox_speed_kd.value() #(module),(data1)(data2),(data3)(...)(#) msg = CMD_PID_SPEED + "," + \ str(speedKpCons) + "," + \ str(speedKiCons) + "," + \ str(speedKdCons) + "#" # Sending UDP packets... if (self.clientUDP != None): self.clientUDP.putMessage(msg) def pushButton_angleZeroPID_onClicked(self): #(module),(data1)(data2),(data3)(...)(#) msg = CMD_PID_ANGLE + "," + \ str(0) + "," + \ str(0) + "," + \ str(0) + "," + \ str(0) + "," + \ str(0) + "," + \ str(0) + "," + \ str(0) + "," + \ str(0) + "#" # Sending UDP packets... if (self.clientUDP != None): self.clientUDP.putMessage(msg) def pushButton_speedZeroPID_onClicked(self): #(module),(data1)(data2),(data3)(...)(#) msg = CMD_PID_SPEED + "," + \ str(0) + "," + \ str(0) + "," + \ str(0) + "#" # Sending UDP packets... if (self.clientUDP != None): self.clientUDP.putMessage(msg) def pushButton_controlSet_onClicked(self): enableArduino = self.ui.checkBox_en_arduino.checkState() print(enableArduino) enableCV = self.ui.checkBox_en_cv.checkState() print(enableCV) #(module),(data1)(data2),(data3)(...)(#) msg = CMD_MANAGER + "," + \ str(enableArduino) + "," + \ str(enableCV) + "#" # Sending UDP packets... if (self.clientUDP != None): self.clientUDP.putMessage(msg)
class Principal(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.conn = None self.cursor = None self.minMoto = 0 self.maxMoto = 0 self.minQuad = 0 self.maxQuad = 0 self.minCar = 0 self.maxCar = 0 self.tmpCountFile = [] self.countZone = [] self.mainWindow = Ui_MainWindow() self.mainWindow.setupUi(self) self.db = DataBase() self.db.open('dakar.sqlite') self.countZones() self.countVehicles() self.path() self.mainTable() #self.inputFiles() self.mainWindow.tblData.resizeRowsToContents() self.mainWindow.tblData.setColumnWidth(1, 70) self.mainWindow.lblWpt.setAlignment(Qt.AlignHCenter) self.mainWindow.lblDz.setAlignment(Qt.AlignHCenter) self.ctimer = QTimer() self.ctimer.start(10000) self.mainWindow.actionCategory.triggered.connect(self.openCategoryWindow) self.mainWindow.actionDirectoryPath.triggered.connect(self.searchPath) self.mainWindow.actionEditZone.triggered.connect(self.openEditZone) self.mainWindow.actionDeleteData.triggered.connect(self.deleteData) self.connect(self.ctimer,SIGNAL("timeout()"), self.checkNewFile) self.mainWindow.tblGralStatus.cellClicked.connect(self.otherTable) self.mainWindow.tblGralStatus.cellChanged.connect(self.saveCell) self.connect(self.mainWindow.btnExit,SIGNAL('clicked()'),self.exit) def path(self): f = open('path.txt') path = f.readline() self.mainWindow.lblPath.setText("Current Path: " + path) def exit(self): exit() def countZones(self): check = self.db.countZone() for i in check: self.countZone.append(i[0]) def mainTable(self): """Show the main table. Search data from sqlite """ rows = self.db.get_tables() self.mainWindow.tblGralStatus.setRowCount(len(rows)) for i,table in enumerate(rows): for m,data in enumerate(table): if m != 0: self.mainWindow.tblGralStatus.setItem(i,m - 1,QTableWidgetItem(str(data).decode("utf-8"))) if str(data) == 'OK': color = QColor(133, 222, 84) elif str(data) == 'NOK': color = QColor(255, 64, 16) else: color = QColor("white") self.mainWindow.tblGralStatus.item(i, m - 1).setBackground(QColor(color)) self.mainWindow.tblGralStatus.item(i, m - 1).setTextAlignment(Qt.AlignCenter) self.mainWindow.tblGralStatus.resizeColumnsToContents() self.mainWindow.tblGralStatus.resizeRowsToContents() self.mainWindow.tblGralStatus.setColumnWidth(1,100) self.mainWindow.tblGralStatus.setColumnWidth(10,308) self.mainWindow.tblGralStatus.setSortingEnabled(True) def openCategoryWindow(self): """Open the windows who´s conteins the parameter of category """ mainWindow = CategoryParam().exec_() def openEditZone(self): mainWindow = EditZone().exec_() def searchPath(self): """Search the path where are the files .csv """ dir_ = QFileDialog.getExistingDirectory(None, 'Select a folder:', 'C:\\', QFileDialog.ShowDirsOnly) f = open('path.txt','w') f.write(dir_) f.close() self.mainWindow.lblPath.setText("Current Path: " + dir_) self.inputFiles() def inputFiles(self): """This section open each .csv file, look in BD if this competitor alredy exist and if not, its add it into BD, then call mainTable """ f = open('path.txt') path = f.readline() self.mainWindow.lblPath.setText("Current Path: " + path) allFiles = glob.glob(path + "/*.csv") self.tmpCountFile = allFiles findWord = False for q,oneFile in enumerate(allFiles): zonePassed = [] f = open( oneFile, 'r') allData = f.readlines() #try: numCompetitorStr = allData[2].split(";")[1] numCompetitor = re.sub("\D", "", numCompetitorStr) try: check = self.db.getDataCompetitor(int(numCompetitor)) except: check = False if check == None: nameCompetitor = " " category = "Moto" if int(numCompetitor) >= self.minMoto and int(numCompetitor) <= self.maxMoto: category = "Moto" elif int(numCompetitor) >= self.minQuad and int(numCompetitor) <= self.maxQuad: category = "Quad" elif int(numCompetitor) >= self.minCar and int(numCompetitor) <= self.maxCar: category = "Car" if int(allData[8].split(";")[1]) == 0: wpt = "OK" else: wpt = "NOK" if int(allData[10].split(";")[1]) == 0: disc = "OK" else: disc = "NOK" try: if int(allData[15].split(";")[1]) == 0: dz = "OK" except: dz = "NOK" dzDismiss = allData[15].split(";") for i,dzValue in enumerate(dzDismiss): if i !=0: self.db.insertDz(int(numCompetitor),dzValue) codNum = int(allData[5].split(";")[1]) version = "2.0" gpsNumber = allData[3].split(";")[1] obs = " " self.db.insertData(int(numCompetitor),nameCompetitor,category,wpt,dz,disc,codNum,version,gpsNumber,obs) for line in allData: try: if findWord: tmpnum = line.split(";")[3] num = tmpnum.split(":")[1] zonePassed.append(int(num)) if line.startswith('InfosChronos') : findWord = True except: pass zoneDismiss = list(set(self.countZone) - set(zonePassed)) for a in zoneDismiss: self.db.insertZoneDismiss(numCompetitor,a) #except: #pass self.countVehicles() self.mainTable() def countVehicles(self): """Count how many different vehicle exist and count each of them, then show it on a text area """ rows = self.db.get_category() self.minMoto = rows[0][2] self.maxMoto = rows[0][3] self.minQuad = rows[1][2] self.maxQuad = rows[1][3] self.minCar = rows[2][2] self.maxCar = rows[2][3] countMoto = 0 countQuad = 0 countCar = 0 rows = self.db.get_tables() for row in rows: if row[1] >= self.minMoto and row[1] <= self.maxMoto: countMoto += 1 elif row[1] >= self.minQuad and row[1] <= self.maxQuad: countQuad += 1 elif row[1] >= self.minCar and row[1] <= self.maxCar: countCar += 1 self.mainWindow.lnCountMoto.setText(str(countMoto)) self.mainWindow.lnCountQuad.setText(str(countQuad)) self.mainWindow.lnCountCar.setText(str(countCar)) def checkNewFile(self): """Check if exist a new and diferent on the folder, if exist a new one then call to inputFiles """ f = open('path.txt') path = f.readline() allFiles = glob.glob(path + "/*.csv") #if len(allFiles) > len(self.tmpCountFile): #self.mainWindow.lblUpdate.setText("Hay nuevos archivos") #self.inputFiles() # else: # self.mainWindow.lblUpdate.setText(" ") def otherTable(self): """This section complete the DR, WPT and Data table from each competitor """ rowSelected = self.mainWindow.tblGralStatus.currentIndex() rowDisc = self.mainWindow.tblGralStatus.item(rowSelected.row(),6) numCompetitor = self.mainWindow.tblGralStatus.item(rowSelected.row(),0) check = self.db.getDataCompetitor(int(numCompetitor.text())) self.mainWindow.tblData.setItem(-1,1,QTableWidgetItem(str(check[1]))) self.mainWindow.tblData.setItem(0,1,QTableWidgetItem(str(check[10]))) self.mainWindow.tblData.setItem(1,1,QTableWidgetItem(str(check[2]).decode("utf-8"))) check = self.db.getDzCompetitor(int(numCompetitor.text())) if len(check) == 0: self.mainWindow.lstDzStatus.clear() self.mainWindow.lstDz.clear() self.mainWindow.lstDzStatus.addItem(QListWidgetItem("OK")) self.mainWindow.lstDzStatus.item(0).setBackground(QColor(133, 222, 84)) self.mainWindow.lstDzStatus.item(0).setTextAlignment(Qt.AlignHCenter) else: self.mainWindow.lstDzStatus.clear() self.mainWindow.lstDz.clear() self.mainWindow.lstDzStatus.addItem(QListWidgetItem("NOK")) self.mainWindow.lstDzStatus.item(0).setBackground(QColor(255, 64, 16)) self.mainWindow.lstDzStatus.item(0).setTextAlignment(Qt.AlignHCenter) self.mainWindow.lblWpt.setAlignment(Qt.AlignHCenter) for m,data in enumerate(check): self.mainWindow.lstDz.addItem(QListWidgetItem("%s"%str(data[0]))) check = self.db.getZoneDismiss(int(numCompetitor.text())) if len(check) == 0: self.mainWindow.lstWptStatus.clear() self.mainWindow.lstWpt.clear() self.mainWindow.lstWptStatus.addItem(QListWidgetItem("OK")) self.mainWindow.lstWptStatus.item(0).setBackground(QColor(133, 222, 84)) self.mainWindow.lstWptStatus.item(0).setTextAlignment(Qt.AlignHCenter) else: self.mainWindow.lstWpt.clear() self.mainWindow.lstWptStatus.clear() self.mainWindow.lstWptStatus.addItem(QListWidgetItem("NOK")) self.mainWindow.lstWptStatus.item(0).setBackground(QColor(255, 64, 16)) self.mainWindow.lstWptStatus.item(0).setTextAlignment(Qt.AlignHCenter) for m,data in enumerate(check): self.mainWindow.lstWpt.addItem(QListWidgetItem("%s"%str(data[0]))) self.mainWindow.lstWpt.item(m).setTextAlignment(Qt.AlignHCenter) self.mainWindow.lstDiscStatus.clear() if rowDisc.text() == 'OK': color = QColor(133, 222, 84) else: color = QColor(255, 64, 16) self.mainWindow.lstDiscStatus.addItem(QListWidgetItem(rowDisc.text())) self.mainWindow.lstDiscStatus.item(0).setBackground(color) self.mainWindow.lstDiscStatus.item(0).setTextAlignment(Qt.AlignHCenter) def deleteData(self): """Delete al data""" self.tmpCountFile = [] self.db.deleteData() self.countVehicles() self.mainTable() def saveCell(self, row, column): """This is for save when put the name or any observation on the main table then will be saved into the BD""" if column == 1: name = self.mainWindow.tblGralStatus.item(row,column).text() idCompetitor = self.mainWindow.tblGralStatus.item(row,0).text() self.db.updateData("nombre",idCompetitor, name) elif column == 10: obs = self.mainWindow.tblGralStatus.item(row,column).text() idCompetitor = self.mainWindow.tblGralStatus.item(row,0).text() self.db.updateData("obs",idCompetitor, obs)
#!/usr/bin/python2 import sys from PyQt4.QtGui import QApplication, QMainWindow from mainWindow import Ui_MainWindow app = QApplication(sys.argv) window = QMainWindow() ui = Ui_MainWindow() ui.setupUi(window) window.show() sys.exit(app.exec_())
class Ui_selectAccount(object): color = "" avatar = "" username = '' name = '' def setUserName(self, userName): self.userName = userName def confirmButtonPressed(self): self.setUserName(self.userName) usercolor = self.color useravatar = self.avatar print("Username: "******"/Users/purepolachan/Desktop/ProjectSEP_final/Register.db") cur = connection.cursor() cur.execute( "UPDATE USERS SET USERAKA=?, USERCOLOR=?, USERAVATAR=? WHERE USERNAME=?", (self.name, usercolor, useravatar, self.userName)) connection.commit() connection.close() self.ui2.setupUi(self.mainwindow) self.mainwindow.show() self.ui.hide() def nextButton(self): self.name = self.getName.text() if self.name: self.label_avatar.raise_() self.green.deleteLater() self.red.deleteLater() self.white.deleteLater() self.cyan.deleteLater() self.yellow.deleteLater() self.ava01.deleteLater() self.ava02.deleteLater() self.ava03.deleteLater() self.nameText.deleteLater() self.getName.deleteLater() self.colorText.deleteLater() self.avatarText.deleteLater() self.anim = QPropertyAnimation(self.label_avatar, b"geometry") self.anim.setDuration(2000) self.anim.setStartValue(QRect(280, 280, 250, 250)) self.anim.setEndValue(QRect(550, 280, 250, 250)) self.confirmButton.deleteLater() self.anim2 = QPropertyAnimation(self.doneButton, b"geometry") self.anim2.setDuration(2000) self.anim2.setStartValue(QRect(830, 600, 141, 51)) self.anim2.setEndValue(QRect(600, 600, 141, 51)) self.anim.start() self.anim2.start() self.userText.setText(self.name) # self.fade = QGraphicsOpacityEffect() def yellowChanged(self, event): self.label_avatar.setStyleSheet("background:yellow") self.color = "yellow" def redChanged(self, event): self.label_avatar.setStyleSheet("background:red") self.color = "red" def cyanChanged(self, event): self.label_avatar.setStyleSheet("background:cyan") self.color = "cyan" def whiteChanged(self, event): self.label_avatar.setStyleSheet("background:white") self.color = "white" def greenChanged(self, event): self.label_avatar.setStyleSheet("background:green") self.color = "green" def av1Changed(self, event): self.label_avatar.setPixmap(QtGui.QPixmap(":/Pic/Pic/avatar01.png")) self.avatar = "avatar01" def av2Changed(self, event): self.label_avatar.setPixmap(QtGui.QPixmap(":/Pic/Pic/avartar02.png")) self.avatar = "avatar02" def av3Changed(self, event): self.label_avatar.setPixmap(QtGui.QPixmap(":/Pic/Pic/avatar03.png")) self.avatar = "avatar03" def setupUi(self, selectAccount): self.ui = selectAccount selectAccount.setObjectName("selectAccount") selectAccount.resize(1440, 900) selectAccount.setMinimumSize(QtCore.QSize(1440, 900)) font = QtGui.QFont() font.setFamily("Optima") selectAccount.setFont(font) selectAccount.setStyleSheet("background-image: url(:/Pic/Pic/bg.png);") self.label_title = QtWidgets.QLabel(selectAccount) self.label_title.setGeometry(QtCore.QRect(250, 140, 1000, 61)) self.label_title.setObjectName("label_title") self.label_avatar = QtWidgets.QLabel(selectAccount) self.label_avatar.setGeometry(QtCore.QRect(280, 280, 250, 250)) self.label_avatar.setStyleSheet("background:white") self.label_avatar.setText("") self.label_avatar.setPixmap(QtGui.QPixmap(":/Pic/Pic/logo_pic.png")) self.label_avatar.setScaledContents(True) self.label_avatar.setObjectName("label_avatar") self.nameText = QtWidgets.QLabel(selectAccount) self.nameText.setGeometry(QtCore.QRect(550, 300, 71, 41)) self.nameText.setObjectName("nameText") self.getName = QtWidgets.QLineEdit(selectAccount) self.getName.setGeometry(QtCore.QRect(650, 300, 221, 41)) self.getName.setStyleSheet("border-radius: 10px;\n" "background: white;\n" "color:black;") self.getName.setObjectName("getName") self.colorText = QtWidgets.QLabel(selectAccount) self.colorText.setGeometry(QtCore.QRect(550, 400, 71, 31)) self.colorText.setObjectName("colorText") self.avatarText = QtWidgets.QLabel(selectAccount) self.avatarText.setGeometry(QtCore.QRect(550, 480, 81, 41)) self.avatarText.setObjectName("avatarText") self.horizontalLayoutWidget = QtWidgets.QWidget(selectAccount) self.horizontalLayoutWidget.setGeometry(QtCore.QRect( 650, 400, 181, 31)) self.horizontalLayoutWidget.setObjectName("horizontalLayoutWidget") self.colorLayout = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget) self.colorLayout.setContentsMargins(0, 0, 0, 0) self.colorLayout.setObjectName("colorLayout") self.red = QtWidgets.QLabel(self.horizontalLayoutWidget) self.red.setStyleSheet("background:red;\n" "") self.red.setText("") self.red.setObjectName("red") self.colorLayout.addWidget(self.red) self.yellow = QtWidgets.QLabel(self.horizontalLayoutWidget) self.yellow.setStyleSheet("background:yellow\n" ";\n" "") self.yellow.setText("") self.yellow.setObjectName("yellow") self.colorLayout.addWidget(self.yellow) self.cyan = QtWidgets.QLabel(self.horizontalLayoutWidget) self.cyan.setStyleSheet("background:cyan;\n" "") self.cyan.setText("") self.cyan.setObjectName("cyan") self.colorLayout.addWidget(self.cyan) self.white = QtWidgets.QLabel(self.horizontalLayoutWidget) self.white.setStyleSheet("background:white;\n" "") self.white.setText("") self.white.setObjectName("white") self.colorLayout.addWidget(self.white) self.green = QtWidgets.QLabel(self.horizontalLayoutWidget) self.green.setStyleSheet("background:green;\n" "") self.green.setText("") self.green.setObjectName("green") self.colorLayout.addWidget(self.green) self.ava02 = QtWidgets.QLabel(selectAccount) self.ava02.setGeometry(QtCore.QRect(760, 460, 100, 100)) self.ava02.setText("") self.ava02.setPixmap(QtGui.QPixmap(":/Pic/Pic/avartar02.png")) self.ava02.setScaledContents(True) self.ava02.setObjectName("ava02") self.ava03 = QtWidgets.QLabel(selectAccount) self.ava03.setGeometry(QtCore.QRect(870, 460, 100, 100)) self.ava03.setText("") self.ava03.setPixmap(QtGui.QPixmap(":/Pic/Pic/avatar03.png")) self.ava03.setScaledContents(True) self.ava03.setObjectName("ava03") self.ava01 = QtWidgets.QLabel(selectAccount) self.ava01.setGeometry(QtCore.QRect(650, 460, 100, 100)) self.ava01.setStyleSheet("border-color: white") self.ava01.setText("") self.ava01.setPixmap(QtGui.QPixmap(":/Pic/Pic/avatar01.png")) self.ava01.setScaledContents(True) self.ava01.setObjectName("ava01") self.doneButton = QtWidgets.QPushButton(selectAccount) self.doneButton.setGeometry(QtCore.QRect(830, 600, 141, 51)) self.doneButton.setObjectName("doneButton") self.doneButton.setStyleSheet("#doneButton{\n" "font: 20pt \"American Typewriter\";\n" "font-weight:bold;\n" "background: rgb(245, 255, 0);\n" "color: rgb(9, 52, 56);\n" "border-radius: 10px;\n" "}\n" "#doneButton:hover{\n" "background: rgb(214, 215, 0);\n" "}") self.confirmButton = QtWidgets.QPushButton(selectAccount) self.confirmButton.setGeometry(QtCore.QRect(830, 600, 141, 51)) font = QtGui.QFont() font.setFamily("American Typewriter") font.setPointSize(20) font.setBold(True) font.setItalic(False) font.setWeight(75) self.confirmButton.setFont(font) self.confirmButton.setStyleSheet( "#confirmButton{\n" "font: 20pt \"American Typewriter\";\n" "font-weight:bold;\n" "background: rgb(245, 255, 0);\n" "color: rgb(9, 52, 56);\n" "border-radius: 10px;\n" "}\n" "#confirmButton:hover{\n" "background: rgb(214, 215, 0);\n" "}") self.confirmButton.setObjectName("confirmButton") self.confirmButton.clicked.connect(self.nextButton) self.doneButton.clicked.connect(self.confirmButtonPressed) self.userText = QtWidgets.QLabel(selectAccount) self.userText.setGeometry(QtCore.QRect(650, 540, 500, 41)) self.userText.setStyleSheet( "font-size:24pt; font-weight:600; color:#ffffff;") # self.cancelButton = QtWidgets.QPushButton(selectAccount) # self.cancelButton.setGeometry(QtCore.QRect(660, 600, 141, 51)) # self.cancelButton.setStyleSheet("#cancelButton{\n" # "font: 20pt \"American Typewriter\";\n" # "font-weight:bold;\n" # "background: white;\n" # " color: rgb(207, 203, 0);\n" # "border-radius: 10px;\n" # "}\n" # "#cancelButton:hover{\n" # "background: rgb(230, 228, 231);\n" # "}") # self.cancelButton.setObjectName("cancelButton") self.retranslateUi(selectAccount) QtCore.QMetaObject.connectSlotsByName(selectAccount) self.yellow.mousePressEvent = self.yellowChanged self.red.mousePressEvent = self.redChanged self.cyan.mousePressEvent = self.cyanChanged self.white.mousePressEvent = self.whiteChanged self.green.mousePressEvent = self.greenChanged self.ava01.mousePressEvent = self.av1Changed self.ava02.mousePressEvent = self.av2Changed self.ava03.mousePressEvent = self.av3Changed def retranslateUi(self, selectAccount): _translate = QtCore.QCoreApplication.translate selectAccount.setWindowTitle(_translate("selectAccount", "Form")) self.label_title.setText( _translate( "selectAccount", "<html><head/><body><p><span style=\" font-size:48pt; font-weight:600; color:#ffffff;\">Firstly, Choose your name and avatar!</span></p><p><br/></p></body></html>" )) self.nameText.setText( _translate( "selectAccount", "<html><head/><body><p><span style=\" font-size:24pt; font-weight:600; color:#ffffff;\">Name</span></p></body></html>" )) self.colorText.setText( _translate( "selectAccount", "<html><head/><body><p><span style=\" font-size:24pt; font-weight:600; color:#ffffff;\">Color</span></p><p><br/></p></body></html>" )) self.avatarText.setText( _translate( "selectAccount", "<html><head/><body><p><span style=\" font-size:24pt; font-weight:600; color:#ffffff;\">Avatar</span></p></body></html>" )) self.ava02.setStyleSheet( _translate("selectAccount", "border-color: white")) self.ava03.setStyleSheet( _translate("selectAccount", "border-color: white")) self.confirmButton.setText(_translate("selectAccount", "Next")) self.doneButton.setText(_translate("selectAccount", "Done"))
class Movies(QtGui.QMainWindow): """Clase principal del programa""" table_columns =( (u"Titulo",100), (u"Director",150), (u"Pais",100), (u"Ranking",75) ) def __init__(self): """Cosntructor del programa""" super(Movies, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.centerWindow() self.loadMovies() self.setSignals() self.show() def centerWindow(self): """Funcion que centra la interfaz grafica en la pantalla""" qr = self.frameGeometry() cp = QtGui.QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) def loadMovies(self): """Funcion que carga la base de datos en la interfaz""" movies = controller.obtener_movies() row = len(movies) model = QtGui.QStandardItemModel( row, len(self.table_columns)) self.ui.tableView.setModel(model) self.ui.tableView.horizontalHeader().setResizeMode(0, self.ui.tableView.horizontalHeader().Stretch) for col, h in enumerate(self.table_columns): model.setHeaderData(col, QtCore.Qt.Horizontal, h[0]) self.ui.tableView.setColumnWidth(col, h[1]) for i, data in enumerate(movies): row = [data[1], data[4], data[5], data[8]] for j, field in enumerate(row): index = model.index(i, j, QtCore.QModelIndex()) model.setData(index, field) def setSignals(self): self.ui.tableView.clicked.connect(self.infoMovies) self.ui.likeButton.clicked.connect(self.rankingUp) self.ui.unlikeButton.clicked.connect(self.rankingDown) def infoMovies(self): index = self.ui.tableView.currentIndex() model = self.ui.tableView.model() codigo = model.index(index.row(), 3, QtCore.QModelIndex()).data() pelicula = controller.infoFila(codigo) direccion = "imgCine/{0}".format(pelicula[1]) self.ui.imgLabel.setPixmap(QtGui.QPixmap(direccion)) title = "{0} \n{1}, {2}".format(pelicula[0], pelicula[2], pelicula[3]) self.ui.titleLabel.setText(title) plot = pelicula[6] self.ui.infoLabel.setText(plot) starring = pelicula[5].split("|") self.ui.starringLabel.setText(starring[0]) def rankingUp(self): index = self.ui.tableView.currentIndex() if index.row() == -1: # No se ha seleccionado una fila errorQMessageBox = QtGui.QMessageBox() errorQMessageBox.setWindowTitle("ERROR!") errorQMessageBox.setText("Debe seleccionar una fila") errorQMessageBox.exec_() else: model = self.ui.tableView.model() index = self.ui.tableView.currentIndex() codigo = model.index(index.row(), 3, QtCore.QModelIndex()).data() if (codigo != 1): codigo2 = model.index(index.row()-1, 3, QtCore.QModelIndex()).data() valores = controller.infoFila(codigo) valores2 = controller.infoFila(codigo2) controller.subir(codigo, valores2) controller.subir(codigo2, valores) else: errorQMessageBox = QtGui.QMessageBox() errorQMessageBox.setWindowTitle("ERROR!") errorQMessageBox.setText(u"Esta pelicula no puede subir más") errorQMessageBox.exec_() self.loadMovies() def rankingDown(self): index = self.ui.tableView.currentIndex() if index.row() == -1: # No se ha seleccionado una fila errorQMessageBox = QtGui.QMessageBox() errorQMessageBox.setWindowTitle("ERROR!") errorQMessageBox.setText("Debe seleccionar una fila") errorQMessageBox.exec_() else: model = self.ui.tableView.model() index = self.ui.tableView.currentIndex() codigo = model.index(index.row(), 3, QtCore.QModelIndex()).data() if (codigo != 7): codigo2 = model.index(index.row()+1, 3, QtCore.QModelIndex()).data() valores = controller.infoFila(codigo) valores2 = controller.infoFila(codigo2) controller.subir(codigo, valores2) controller.subir(codigo2, valores) else: errorQMessageBox = QtGui.QMessageBox() errorQMessageBox.setWindowTitle("ERROR!") errorQMessageBox.setText(u"La pelicula esta al tope de lo profundo") errorQMessageBox.exec_() self.loadMovies()
class Main(QtGui.QMainWindow): input_file = '' # Menbe hujjiti output_file = '' # Nishah hujjiti isSetFile = False # Ensure the input file is selected def __init__(self): QtGui.QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.btnConvert.clicked.connect(self.btnConvert_clicked) # self.ui.btnDefault.clicked.connect(self.btnDefault_clicked) self.ui.actionInput_File.triggered.connect(self.selectInputFile) self.ui.actionOutput_File.triggered.connect(self.setOutputFile) def btnConvert_clicked(self): if self.isSetFile == False: src_txt = unicode (self.ui.te_src.toPlainText().toUtf8(), "utf-8") opt_txt = unicode (self.ui.te_opt.toPlainText().toUtf8(), "utf-8") else: # This part should change to status bar msgBox = QtGui.QMessageBox() msgBox.setText("Converting the source file. \n Menbe hujitini aylandurwatimiz.") msgBox.exec_() inf = open(self.input_file, 'r') src_txt = unicode (inf.read(), "utf-8") inf.close() from_val = self.ui.cb_src.currentIndex() to_val = self.ui.cb_opt.currentIndex() usc = UgScriptConverter() # 0 Uyghur, 1 Latin, 2 Common Turkish if from_val == to_val: opt_txt = src_txt # Uyghur Arabic elif from_val == 0: if to_val == 1: # Uyghur to Latin opt_txt = usc.UA2LA(src_txt) elif to_val == 2: # Uyghur to Common Turkish opt_txt = usc.UA2CT(src_txt) elif to_val == 3: # Uyghur to Cyrilik Turkish opt_txt = usc.UA2CC(src_txt) # Latin elif from_val == 1: if to_val == 0: # Latin to Uyghur opt_txt = usc.LA2UA(src_txt) elif to_val == 2: # Latin to Common Turkish opt_txt = usc.LA2CT(src_txt) elif to_val == 3: # Latin to Cyrilik opt_txt = usc.LA2CC(src_txt) # Common TUrkish elif from_val == 2: if to_val == 0: # Common Turkish to Uyghur opt_txt = usc.CT2UA(src_txt) elif to_val == 1: # Common Turkish to Latin opt_txt = usc.CT2LA(src_txt) elif to_val == 3: # Common Turkish to Cyrilik opt_txt = usc.CT2CC(src_txt) # Cyrilik elif from_val == 3: if to_val == 0: # Common Turkish to Uyghur opt_txt = usc.CC2UA(src_txt) elif to_val == 1: # Common Turkish to Latin opt_txt = usc.CC2LA(src_txt) elif to_val == 2: # Common Turkish to Cyrilik opt_txt = usc.CT2CC(src_txt) if self.isSetFile == False: self.ui.te_opt.setText(opt_txt) else: of = open(self.output_file, 'w') of.write(opt_txt.encode('utf8')) of.close() isSetFile = False print "Converting is done." # print from_val # print to_val # text = u"ھەممە ئادەم تۇغۇلۇشىدىنلا ئەركىن، ئىززەت-ھۆرمەت ۋە ھوقۇقتا باب-باراۋەر بولۇپ تۇغۇلغان."+\ # u' ئۇلار ئەقىلگە ۋە ۋىجدانغا ئىگە ھەمدە بىر-بىرىگە قېرىنداشلىق مۇناسىۋىتىگە'+\ # u" خاس روھ بىلەن مۇئامىلە قىلىشى كېرەك." # latin_text = u"Hemme adem tughulushidinla erkin, izzet-hörmet we hoquqta bab-barawer "+\ # u"bolup tughulghan. Ular eqilge we wijdan'gha ige hemde bir-birige qérindashliq munasiwitige "+\ # u"xas roh bilen muamile qilishi kérek." # ct_text = u"Hemme adem tuğuluşidinla erkin, izzet-hörmet ve hoquqta bab-baraver bolup tuğulğan."+\ # u" Ular eqilge ve vijdanğa ige hemde bir-birige qérindaşliq munasivitige xas roh bilen mu'amile qilişi kérek. ? <<>>" # # latin_text = "adem adem" # self.ui.te_src.setText(ct_text) # usc = UgScriptConverter() # # ug_text = usc.CT2UA(ct_text) # # self.ui.textEdit_2.setText(ug_text) # # sys.exit() # ug_text = usc.LA2UA(latin_text) # self.ui.te_opt.setText(ug_text) # ct_text= usc.LA2CT(latin_text) # self.ui.te_opt.setText(ct_text) # This function for testing def btnDefault_clicked(self): inf = open('default.txt', 'r') ug_text = unicode (inf.read(), "utf-8") inf.close() from_val = self.ui.cb_src.currentIndex() if from_val == 0: self.ui.te_src.setText(ug_text) elif from_val == 1: pass elif from_val == 1: pass elif from_val == 1: pass elif from_val == 1: pass else: pass def selectFile(self): tmp_file = (QtGui.QFileDialog.getOpenFileName()) return tmp_file def selectInputFile(self): self.input_file = self.selectFile() self.output_file = self.input_file + '_convert.txt' print "Input file is selected." print 'Input: ', self.input_file print 'Output: ', self.output_file self.isSetFile = True def setOutputFile(self): if self.isSetFile == False: msgBox = QtGui.QMessageBox() msgBox.setText("Please choose the source file. \n Menbe hujitini tallang.") msgBox.exec_() return self.output_file = self.selectFile() print 'Input: ', self.input_file print 'Output: ', self.output_file
class Application(QtWidgets.QMainWindow): def __init__(self, parent=None): super(Application, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) # enable drag and drop self.setAcceptDrops(True) # set matplotlib FigureCanvas self.fig = Figure() self.FigureCanvas = FigureCanvas(self.fig) self.ax1 = self.fig.add_subplot(1, 1, 1) self.ax1.set_axis_off() self.ui.imageLayout.addWidget(self.FigureCanvas) # button self.ui.pushButton_save.clicked.connect(self.onClick_save) def dragEnterEvent(self, e): if e.mimeData().hasFormat('text/uri-list'): e.accept() else: e.ignore() def dropEvent(self, e): # ファイルパスを取得する urls = e.mimeData().text().split("\n") self.filepath = urls[0][8:] # display image self.image = io.imread(self.filepath) self.binimage = self.image > threshold_otsu(self.image) # labeling self.label = label(self.binimage) for l in regionprops(self.label): # add item item = QtWidgets.QListWidgetItem(str(l.label)) self.ui.listWidget.addItem(item) self.plotImage() self.ui.listWidget.itemSelectionChanged.connect( self.onItemSelectionChanged) def plotImage(self): # image self.viewImage = np.zeros(self.image.shape) for item in self.ui.listWidget.selectedItems(): l = int(item.text()) self.viewImage[self.label == l] = 1 self.ax1.clear() self.ax1.imshow(self.viewImage, cmap='gray') self.ax1.set_axis_off() # redraw self.FigureCanvas.draw() def onClick_save(self): # show file chooser savename = QtWidgets.QFileDialog.getSaveFileName( self, 'save file', os.path.dirname(self.filepath), "PNG Image (*.png)") if savename[0]: print(savename[0]) io.imsave(savename[0], self.viewImage * 255) def onItemSelectionChanged(self): self.plotImage()
class main(QtWidgets.QMainWindow, Ui_MainWindow): def __init__(self): super(main, self).__init__() self.ui = None self.monitorDir = "" self.setupUI() #顯示無邊框 self.setWindowFlags(QtCore.Qt.FramelessWindowHint) #顯示全螢幕 self.showFullScreen() self.showMaximized() self.fileSystemWatcher = QtCore.QFileSystemWatcher() self.fileSystemWatcher.addPath(self.monitorDir) self.fileSystemWatcher.directoryChanged.connect(self.__autorun) self.xyzList = [] self.datas = dataCollection() def setupUI(self): self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.pushButton_3.clicked.connect(self.__callRTDialog) self.setupViewer() self.ui.progressBar.setVisible(0) self.ui.verticalLayout_3.addWidget(self.viewer) self.ui.close.clicked.connect(self.close) self.ui.circleRed.clicked.connect(self.close) self.ui.circleYellow.clicked.connect(self.showMinimized) self.ui.automode.clicked.connect(self.__autorun) self.ui.loadsettings.clicked.connect(self.__loadsettings) self.ui.monPath.clicked.connect(self.__addMonitorDir) return def setupViewer(self): self.frame = Qt.QFrame() self.viewer = vtkXYZviewer.XYZviewer(self.frame, 0) self.viewer.setCubeAxesVisibility(True) self.viewer.setScalarBar(0.2, 400, 60, 400) def __callRTDialog(self): self.rtDg = icpRegistration_dialog.treeViewApp() self.rtDg.show() return def __autorun(self): if self.monitorDir == "": self.ui.information.append("尚未選擇自動路徑!") return if self.ui.automode.isChecked(): d = self.monitorDir files = os.listdir(d) for i in files: if ".xyz" in i: if not i in self.xyzList: self.ui.information.append(i) self.xyzList.append(i) p = os.path.join(d, i) self.__qThreadLoading(p) #pcd = tools.getVtkPointCloud(path,1) #self.datas.names.append(i) #self.datas.addData(pcd) #self.__mergedByTransInit() def __qThreadLoading(self, file_path): self.loading = loading(file_path, self.datas) self.datas.isBusy = True self.loading.finished.connect(self.__loadingFinished) self.ui.progressBar.show() self.loading.start() def __loadingFinished(self): self.datas.isBusy = False #self.__mergedByTransInit() self.ui.progressBar.hide() self.viewer.add_newData(self.datas.pcdCollection[-1]) self.ui.information.append("載入完成") def __loadsettings(self): fpath, filetype = QtWidgets.QFileDialog.getOpenFileName( self, "讀取參數", "D:\\", "db files(*.db)") if fpath == "": return trans_inits = tools.loadTrans_init(fpath) self.datas.trans_inits = trans_inits text = "load " + str(len(self.datas.trans_inits)) + "組參數" print(text) print("Load trans_init: ", self.datas.trans_inits) self.ui.information.append(text) return def __addMonitorDir(self): fpath = QtWidgets.QFileDialog.getExistingDirectory( self, "Select", "D:\\") if fpath == "": return files = os.listdir(fpath) for i in files: f = os.path.join(fpath, i) os.remove(f) self.monitorDir = fpath self.fileSystemWatcher.addPath(fpath) text = "Select monitor folder: " + fpath self.ui.information.append(text) return def __mergedByTransInit(self): #1.viewer裡面沒東西, 直接顯示 #2. viewer裡面有點雲, a.判斷要套用哪一組RT b. 套用並合併 c. 只留下合併後點雲 counter = self.datas.mergedCounter print(counter) rtCount = len(self.datas.trans_inits) rtInd = counter print("###############################################") print("current merged count:", rtInd, "Trans count: ", rtCount) print("###############################################") if self.viewer.ind == "" or rtCount == rtInd: self.viewer.add_newData(self.datas.pcdCollection[-1]) self.datas.mergedCounter = 0 else: print("start merged") trans = self.datas.trans_inits print(self.datas.pcdCollection[-2]) print(self.datas.pcdCollection[-1]) print(trans) d = tools.applyTransform(self.datas.pcdCollection[-2], self.datas.pcdCollection[-1], trans[0]) self.datas.pcdCollection = [] self.datas.addData(d) self.viewer.add_newData(self.datas.pcdCollection[-1]) self.datas.mergedCounter += 1 print("mergedCounter:", self.datas.mergedCounter) def closeEvent(self, event): self.viewer.closeWindow() time.sleep(1)
class Recorder(QMainWindow): '''Main Window - menu toolbar to load and save session, open plotter and set server - dock widget holding session and run information - grid plot to stream current emg data of 16 channels - start, stop, progressbar and trigger for current run ''' def __init__(self, parent=None): super(Recorder, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.plotter = None self.session = None self.server = DelsysStation(parent=self) self.ui.dockWidget.setWidget(QWidget()) self.dockLayout = QGridLayout(self.ui.dockWidget.widget()) self.showSessionMeta = None self.showRunMeta = None self.plotWidget = None self.plots = [] self.startTime = datetime.now() self.pinger = QTimer(self) # timer to read data from server whenever available self.runPinger = QTimer(self) # timer to call stop when run duration times out self.runPinger.setSingleShot(True) self.runPinger.timeout.connect(self.stop) self.pinger.timeout.connect(self.ping) self.kinectRecorder=None self.newpath=None self.notSavedState = False def clearDock(self): ''' clear session (dock widget elements) - remove showSessionMeta - remove showRunMeta - kill kinectRecorder - remove session if changes are not saved, ask ''' if self.showSessionMeta is not None: reply = QMessageBox.question(self, 'QMessageBox.question()', 'Do you want to first save the current session?', QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel) if reply == QMessageBox.Yes: self.save() elif reply == QMessageBox.Cancel: return self.session = None self.dockLayout.removeWidget(self.showSessionMeta) self.dockLayout.removeWidget(self.showRunMeta) self.showSessionMeta.deleteLater() self.showRunMeta.deleteLater() self.showSessionMeta = None self.showRunMeta = None self.kinectRecorder.killRecorder() def preparePlots(self): '''arange 2x8 plots for each channel and set parameters ''' if self.ui.frame.layout() is None: layout = QGridLayout() self.ui.frame.setLayout(layout) else: ######### # reset # ######### layout = self.ui.frame.layout() layout.removeWidget(self.plotWidget) self.plotWidget = None self.plots = [] self.plotWidget = pg.GraphicsLayoutWidget(border=(100,100,100)) layout.addWidget(self.plotWidget) for i in range(8): for k in range(2): self.plots.append(self.plotWidget.addPlot(title="EMG " + str(k+2*i+1))) self.plots[-1].plot(np.linspace(0,2,1000)) self.plots[-1].setYRange(-0.0002, 0.0002) self.plotWidget.nextRow() self.plotWidget.show() def setServer(self): ''' open dialog to set server address e.g. localhost, 192.168.1.5 ''' text, ok = QInputDialog.getText(self, "Set server", 'Enter server adress') if ok: self.server.host = text def newSession(self): ''' create new session: - clear dock - open dialog to set session parameters - create showSessionMeta, showRunMeta, kinectRecorder ''' self.clearDock() sessionDialog = SessionDialog(self) if sessionDialog.exec_(): newpath = os.path.join(sessionDialog.ui.leDir.text(), sessionDialog.ui.leName.text()) if not os.path.isdir(newpath): os.makedirs(newpath) else: print('reusing folder') QMessageBox.information(self, 'Warning!', '''You\'re reusing the subject folder''', QMessageBox.Ok) self.session = Session(sessionDialog.ui.leName.text(), sessionDialog.ui.teBemerkung.toPlainText(), newpath) self.showSessionMeta = sessionView(self.session, self) self.showRunMeta = RunWidget(self) self.showRunMeta.ui.leCurrentRun.setText(str(len(self.session.runs))) try: self.kinectRecorder=KinectRecorder() except: print "no Kinect recording" self.kinectRecorder = None self.showSessionMeta.ui.showBemerkung.textChanged.connect(self.pendingSave) self.showRunMeta.ui.lwRuns.itemDoubleClicked.connect(self.openPlotter) self.dockLayout.addWidget(self.showSessionMeta) self.dockLayout.addWidget(self.showRunMeta) self.showRunMeta.show() self.showSessionMeta.show() self.preparePlots() self.ui.tbStart.setEnabled(True) def pendingSave(self): self.notSavedState = True self.setWindowTitle("PyTrigno(*)") def save(self): self.notSavedState = False self.setWindowTitle("PyTrigno") self.session.remarks = self.showSessionMeta.ui.showBemerkung.toPlainText() self.session.dump("ReadMe.txt") def startRun(self): ''' start a recording: - setup server - setup timer (if no eternity is toggled) - setup progress bar - setup buttons - setup session - start recorder ''' #setup server self.server.exitFlag = False try: self.startTime = datetime.now() self.server.start() except: print("something went wrong") self.server.exitFlag = True raise socket.timeout("Could not connect to Delsys Station") else: if self.showRunMeta.ui.cbEternity.checkState() == 0: duration = self.showRunMeta.ui.timeEdit.time() d = duration.second() + duration.minute()*60 self.runPinger.start(d*1000) self.ui.elapsedTime.setRange(0,d) elif self.showRunMeta.ui.cbEternity.checkState() == 2: self.ui.elapsedTime.setRange(0,0) self.pinger.start() self.ui.tbStop.setEnabled(True) self.ui.tbTrigger.setEnabled(True) self.ui.tbStart.setEnabled(False) name = self.showRunMeta.ui.leCurrentRun.text() self.session.addRun(name) if self.kinectRecorder is not None: self.kinectRecorder.startRecording(self.newpath+'\\'+name+'.oni') self.ui.elapsedTime.setRange(0,d) def stop(self): ''' stop recording due to button press or timeout - setup buttons - stop timers - stop server - kill kinectRecorder - add item to list of runs ''' self.ui.tbStop.setEnabled(False) self.ui.tbTrigger.setEnabled(False) self.ui.tbStart.setEnabled(True) self.ui.elapsedTime.reset() QListWidgetItem(self.showRunMeta.ui.leCurrentRun.text(), self.showRunMeta.ui.lwRuns) self.showRunMeta.ui.leCurrentRun.setText(str(len(self.session.runs))) self.server.exitFlag = True self.server.stop() self.runPinger.stop() self.pinger.stop() self.session.stopRun(self.server.buffer) self.server.buffer = None if self.kinectRecorder is not None: self.kinectRecorder.stopRecording() self.server.flush() def trigger(self): ''' add a trigger ''' print("trigger") trigger = self.server.buffer[0].shape[1] self.session.addTrigger(trigger) def ping(self): ''' update progress bar and plots everytime new data is available ''' elapsed = int((datetime.now()-self.startTime).total_seconds()) self.ui.elapsedTime.setValue(elapsed) for p in range(len(self.plots)): if self.server.buffer[0].shape[1] < 5000: self.plots[p].plot(self.server.buffer[0][p], clear=True) else: self.plots[p].plot(self.server.buffer[0][p,-5000:], clear=True) def openPlotter(self, item=None): if self.plotter is None: self.plotter = Plotter() if item is not None: self.plotter.load([os.path.join(self.session.dir, item.text()) + ".pk"]) self.plotter.show() def closeEvent(self, event): if self.notSavedState: reply = QMessageBox.question(self, 'QMessageBox.question()', 'Do you want to first save the current session?', QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel) else: reply = QMessageBox.No if reply == QMessageBox.Yes: self.save() elif reply == QMessageBox.Cancel: event.ignore() return if not self.server.exitFlag: self.stop() event.accept()
class ApplicationWindow(QtWidgets.QMainWindow): messageChanged = pyqtSignal() def __init__(self): super(ApplicationWindow, self).__init__() self.message = [] self.messageChanged.connect(self.decodeMessage) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.graphSettings() self.ui.messageEditBox.returnPressed.connect( self.ui.sendMessageButton.click) self.ui.sendMessageButton.clicked.connect(self.refreshSendMessagePage) def setMessage(self, value): self.message.append(value) self.messageChanged.emit() def decodeMessage(self): if len(self.message) != 0: graph_title = None if self.message[-1] == 'NRZ Unipolar Encoded': graph_title = self.message[-1] elif self.message[-1] == 'NRZ-Invert Encoded': graph_title = self.message[-1] elif self.message[-1] == 'NRZ-Level Encoded': graph_title = self.message[-1] elif self.message[-1] == 'RZ Encoded': graph_title = self.message[-1] if graph_title != None: self.message.pop() binary_code_separated_by_character = [] for encoded_character in self.message: aux = ''.join( decodeMesage(encoded_character, decode_type=graph_title)) binary_code_separated_by_character.append(aux) message_separated_by_character = [] for binary_character in binary_code_separated_by_character: message_separated_by_character.append( binToString(binary_character)) self.refreshReceiveMessagePage(message_separated_by_character, graph_title) self.message = [] def refreshReceiveMessagePage(self, decoded_message, graph_title): _translate = QtCore.QCoreApplication.translate string = ''.join(decoded_message) binary_string = toBin(string, withSpace=True) encoded_message = encodeMesage(binary_string, graph_title) # Repetimos a mensagem no label coreto. self.ui.showMessageLabel1.setText(_translate("MainWindow", string)) # Colocamos o codigo binario no label correto. self.ui.showBinaryLabel1.setText( _translate("MainWindow", binary_string)) # Colocamos a mesangem codificada no label correto. self.ui.showEncoddLabel1.setText( _translate("MainWindow", ' '.join(self.message))) binary_string = toBin(string, withSpace=False) encoded_message = encodeMesage(binary_string, graph_title) self.setGraphReceiveMessagePage(encoded_message, graph_title) def refreshSendMessagePage(self, MainWindow): _translate = QtCore.QCoreApplication.translate string = self.ui.messageEditBox.text() binary_string = toBin(string, withSpace=False) # Exemplo de como ver se o checkbox está ativo if self.ui.checkBoxNRZ.checkState() == QtCore.Qt.Checked: graph_title = 'NRZ Unipolar Encoded' elif self.ui.checkBoxNRZ_I.checkState() == QtCore.Qt.Checked: graph_title = 'NRZ-Invert Encoded' elif self.ui.checkBoxNRZ_L.checkState() == QtCore.Qt.Checked: graph_title = 'NRZ-Level Encoded' elif self.ui.checkBoxRZ.checkState() == QtCore.Qt.Checked: graph_title = 'RZ Encoded' # Mostramos a mensagem no label coreto. self.ui.showMessageLabel0.setText(_translate("MainWindow", string)) binary_code_separated_by_character = toBin(string, withSpace=True) binary_code_separated_by_character = binary_code_separated_by_character.split( ) # Mostramos o codigo binario no label correto. self.ui.showBinaryLabel0.setText( _translate("MainWindow", ' '.join(binary_code_separated_by_character))) encoded_message_separated_by_character = [] for binary_character in binary_code_separated_by_character: aux = ''.join( encodeMesage(binary_character, encode_type=graph_title)) encoded_message_separated_by_character.append(aux) # Mostramos a mesangem codificada no label correto. self.ui.showEncodedLabel0.setText( _translate("MainWindow", ' '.join(encoded_message_separated_by_character))) # Mostrar o grafico encoded_message = encodeMesage(binary_string, encode_type=graph_title) self.graphSettings() self.setGraphSendMessagePage(encoded_message, graph_title) for encoded_character in encoded_message_separated_by_character: sendMessageSocket(encoded_character) sendMessageSocket(graph_title) def setGraphSendMessagePage(self, encoded_message, graph_title): xdados = [] ydados = [] contador = 0 for x in encoded_message: #Lista de dados do eixo y if contador != 0 and ydados[-1] == int(x): contador = contador + 1 xdados.append(contador) ydados.append(int(x)) else: xdados.append(contador) contador = contador + 1 xdados.append(contador) ydados.append(int(x)) ydados.append(int(x)) pen = pg.mkPen(color=(0, 128, 0), width=4) self.ui.graphicsView.clear() self.ui.graphicsView.setTitle(graph_title, color=(0, 0, 0)) self.ui.graphicsView.plot(xdados, ydados, pen=pen) def setGraphReceiveMessagePage(self, encoded_message, graph_title): xdados = [] ydados = [] contador = 0 for x in encoded_message: #Lista de dados do eixo y if contador != 0 and ydados[-1] == int(x): contador = contador + 1 xdados.append(contador) ydados.append(int(x)) else: xdados.append(contador) contador = contador + 1 xdados.append(contador) ydados.append(int(x)) ydados.append(int(x)) pen = pg.mkPen(color=(0, 128, 0), width=4) self.ui.graphicsView1.clear() self.ui.graphicsView1.setTitle(graph_title, color=(0, 0, 0)) self.ui.graphicsView1.plot(xdados, ydados, pen=pen) def graphSettings(self): axis_pen = pg.mkPen(color=(0, 0, 0), width=1, style=QtCore.Qt.DashLine) self.ui.graphicsView.setBackground('w') self.ui.graphicsView.getAxis('left').setPen(color=(0, 0, 0)) self.ui.graphicsView.getAxis('left').setTickSpacing(100, 0.5) self.ui.graphicsView.getAxis('left').setPen(axis_pen) self.ui.graphicsView.getAxis('left').setStyle(tickTextHeight=10) self.ui.graphicsView.getAxis('bottom').setPen(color=(0, 0, 0)) self.ui.graphicsView.getAxis('bottom').setTickSpacing(100, 1) self.ui.graphicsView.getAxis('bottom').setPen(axis_pen) self.ui.graphicsView.showGrid(x=True, y=True, alpha=1) self.ui.graphicsView.getViewBox().setYRange(-3.5, 3.5) self.ui.graphicsView.getViewBox().setXRange(0, 20) self.ui.graphicsView.getViewBox().border = pg.mkPen(color=(0, 0, 0), width=2) self.ui.graphicsView.setTitle('Encoded Graphs', color=(0, 0, 0)) self.ui.graphicsView1.setBackground('w') self.ui.graphicsView1.getAxis('left').setPen(color=(0, 0, 0)) self.ui.graphicsView1.getAxis('left').setTickSpacing(100, 0.5) self.ui.graphicsView1.getAxis('left').setPen(axis_pen) self.ui.graphicsView1.getAxis('left').setStyle(tickTextHeight=10) self.ui.graphicsView1.getAxis('bottom').setPen(color=(0, 0, 0)) self.ui.graphicsView1.getAxis('bottom').setTickSpacing(100, 1) self.ui.graphicsView1.getAxis('bottom').setPen(axis_pen) self.ui.graphicsView1.showGrid(x=True, y=True, alpha=1) self.ui.graphicsView1.getViewBox().setYRange(-3.5, 3.5) self.ui.graphicsView1.getViewBox().setXRange(0, 20) self.ui.graphicsView1.getViewBox().border = pg.mkPen(color=(0, 0, 0), width=2) self.ui.graphicsView1.setTitle('Encoded Graphs', color=(0, 0, 0))
import sys from PyQt5 import QtWidgets from mainWindow import Ui_MainWindow if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) # Instantiate widgets and models self.toolBar = ToolBar() self.addToolBar(self.toolBar) self.dirModel = TableModel(dict()) self.imageModel = QStandardItemModel() self.ui.dockWidget.setTitleBarWidget(QtWidgets.QWidget()) self.statusBarLabel = QtWidgets.QLabel() self.statusBar().addWidget(self.statusBarLabel) self.cmapMenu = QtWidgets.QMenu() self.in_directory = None # Cmap menu Config.cmap = 'bone' self.create_cmap_menu() # Toolbar self.toolBar.refreshButton.triggered.connect(self.create_dir_model) self.toolBar.saveButton.triggered.connect(self.export_df) self.toolBar.loadButton.triggered.connect(self.load_df) # Directory list view self.ui.dirView.clicked.connect(self.change_image_grid) # Image view image_size = QtCore.QSize(400, 400) # Set icon sizing here grid_size = QtCore.QSize(450, 450) self.ui.imageView.setModel(self.imageModel) self.ui.imageView.setViewMode(QtWidgets.QListView.IconMode) self.ui.imageView.setIconSize(image_size) self.ui.imageView.setGridSize(grid_size) self.ui.imageView.clicked.connect(self.image_selected) # Final touches self.update_statusbar() ################################################################ def create_cmap_menu(self): self.cmapMenu.clear() for cmap_type, cmaps in Config.cmaps.items(): thisMenu = QtWidgets.QMenu(cmap_type) self.cmapMenu.addMenu(thisMenu) for cmap in cmaps: thisAction = QtWidgets.QAction(cmap, self.cmapMenu) thisAction.triggered.connect(self.update_cmap) thisMenu.addAction(thisAction) self.toolBar.cmapButton.setMenu(self.cmapMenu) def update_cmap(self, args): Config.cmap = self.sender().text() self.change_image_grid(self.ui.dirView.currentIndex()) self.update_statusbar() ################################################################ def update_statusbar(self): self.statusBarLabel.setText( f'Colormap: {Config.cmap} | Directories loaded: {self.dirModel.rowCount()}' ) ################################################################ def create_dir_model(self): self.in_directory = QtWidgets.QFileDialog.getExistingDirectory( self, 'Study Directory', os.path.expanduser('~')) dict_table = {} for root, _, files in os.walk(self.in_directory): if not files: continue dir_name = root.split(os.sep)[-1] total_files = len(files) selected = pd.NA dict_table[dir_name] = { 'TOTAL FILES': total_files, 'SELECTED': selected } self.dirModel = TableModel(dict_table) self.ui.dirView.setModel(self.dirModel) self.ui.dirView.horizontalHeader().setSectionResizeMode( QtWidgets.QHeaderView.Stretch) self.update_statusbar() self.toolBar.cmapButton.setEnabled(True) self.toolBar.saveButton.setEnabled(True) self.toolBar.loadButton.setEnabled(True) ################################################################ def change_image_grid(self, index): self.imageModel.clear() # Get dir path from the index data itself directory = self.dirModel.list_keys[index.row()] dir_path = os.path.join(self.in_directory, directory) previously_checked = self.dirModel.dict_studies[directory]['SELECTED'] # Parse arrays within the directory image_list = [ os.path.join(dir_path, i) for i in os.listdir(dir_path) if i.endswith('.bmeii') ] loaded_images = loader(image_list) for img_path in loaded_images: img_pixmap = QPixmap.fromImage(QImage(img_path)) filename = os.path.basename(img_path).replace('.png', '') imageItem = QStandardItem() imageItem.setIcon(img_pixmap) imageItem.setText(filename) imageItem.setEditable(False) imageItem.setCheckable(True) if not pd.isnull(previously_checked): if filename in previously_checked: imageItem.setCheckState(QtCore.Qt.CheckState.Checked) self.imageModel.appendRow(imageItem) def image_selected(self, index): current_row = self.ui.dirView.currentIndex().row() current_dir = self.dirModel.list_keys[current_row] images_selected = [] for row in range(self.imageModel.rowCount()): item = self.imageModel.item(row) if item.checkState() == QtCore.Qt.CheckState.Checked: item_text = item.text() images_selected.append(item_text) if images_selected == []: self.dirModel.dict_studies[current_dir]['SELECTED'] = pd.NA else: self.dirModel.dict_studies[current_dir][ 'SELECTED'] = images_selected # TODO # self.dirModel.dataChanged.emit() ################################################################ def export_df(self): rows = [] for directory, values in self.dirModel.dict_studies.items(): files = values['SELECTED'] rows.append((directory, files)) df_studies = pd.DataFrame(rows, columns=['DIRECTORY', 'FILES']) df_studies.to_csv( os.path.join(os.path.expanduser('~'), 'SelectedFiles.csv')) def load_df(self): in_csv = QtWidgets.QFileDialog.getOpenFileName( self, 'Load exported file list', os.path.expanduser('~')) try: df = pd.read_csv(in_csv[0]) self.dirModel.update_from_loaded(df) except KeyboardInterrupt: self.statusBarLabel.setText( 'No file selected / Error loading saved list') return
class MainWindow (QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self)
class MyDialog(QtGui.QMainWindow): correctAnswers = 0 tmpsubnet = [[0, 0], [128, 0], [192, 0], [224, 0], [240, 0], [248, 0], [252, 0], [254, 0], [255, 0], [255, 128], [255, 192], [255, 224], [255, 240]] tmpsubnet2 = [[255, 255], [127, 255], [63, 255], [31, 255], [15, 255], [7, 255], [3, 255], [1, 255], [0, 255], [0, 127], [0, 63], [0, 31], [0, 15]] def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.pushButton.clicked.connect(self.check) self.generate() def generate(self): self.flag = 0 self.ip = [ randint(0, 255), randint(0, 255), randint(0, 255), randint(0, 255) ] self.tmp = randint(0, 12) self.subnet = [ 255, 255, self.tmpsubnet[self.tmp][0], self.tmpsubnet[self.tmp][1] ] self.ui.label_ip.setText("{:d}.{:d}.{:d}.{:d}".format( self.ip[0], self.ip[1], self.ip[2], self.ip[3])) self.ui.label_mask.setText("{:d}.{:d}.{:d}.{:d}".format( self.subnet[0], self.subnet[1], self.subnet[2], self.subnet[3])) self.ui.lineEdit_network.setText("") self.ui.lineEdit_network.setFocus() self.ui.lineEdit_bcast.setText("") def check(self): ansNetwork = [ self.ip[0] & self.subnet[0], self.ip[1] & self.subnet[1], self.ip[2] & self.subnet[2], self.ip[3] & self.subnet[3] ] ansBcast = [ self.ip[0], self.ip[1], self.ip[2] | self.tmpsubnet2[self.tmp][0], self.ip[3] | self.tmpsubnet2[self.tmp][1] ] try: usrNetwork = [ int(n) for n in self.ui.lineEdit_network.text().split(".") ] except ValueError: usrNetwork = [0, 0, 0, 0] if usrNetwork[0] == ansNetwork[0] and usrNetwork[1] == ansNetwork[ 1] and usrNetwork[2] == ansNetwork[2] and usrNetwork[ 3] == ansNetwork[3]: self.flag = self.flag + 1 else: self.ui.textEdit_log.append( "Network address is incorrect! The answer is {:d}.{:d}.{:d}.{:d}" .format(ansNetwork[0], ansNetwork[1], ansNetwork[2], ansNetwork[3])) try: usrBcast = [ int(n) for n in self.ui.lineEdit_bcast.text().split(".") ] except ValueError: usrBcast = [0, 0, 0, 0] if usrBcast[0] == ansBcast[0] and usrBcast[1] == ansBcast[ 1] and usrBcast[2] == ansBcast[2] and usrBcast[3] == ansBcast[ 3]: self.flag = self.flag + 1 else: self.ui.textEdit_log.append( "Broadcast address is incorrect! The answer is {:d}.{:d}.{:d}.{:d}" .format(self.ip[0], self.ip[1], ansBcast[2], ansBcast[3])) if self.flag == 2: self.correctAnswers = self.correctAnswers + 1 self.ui.textEdit_log.append("You have " + str(self.correctAnswers) + " correct answers.\n") self.generate()
class SerialWidget(QWidget): def __init__(self, port=None, baud=None, connect_on_start=False): super(SerialWidget, self).__init__() self.ser = None self.reader = CReader() self.writer = CWriter() self.ui = Ui_MainWindow() self.setupUi() self.connected = False if port is not None: curIndex = self.ui.portsComboBox.findText(port) if curIndex > -1: self.ui.portsComboBox.setCurrentIndex(curIndex) self.port = port if baud is not None and baud in baudRates: self.ui.baudRateComboBox.setCurrentIndex(self.ui.baudRateComboBox.findText(baud)) self.baud = baud if connect_on_start and self.baud is not None and self.port is not None: self.connect() def setupUi(self): self.ui.setupUi(self) self.ui.baudRateComboBox.addItems(baudRates) self.refreshPorts() # QObject.connect(self.ui.exitPushButton, SIGNAL("clicked()"), self, SLOT("close()")) QObject.connect(self.ui.refreshPortsPushButton, SIGNAL("clicked()"), self.refreshPorts) QObject.connect(self.ui.connectPushButton, SIGNAL("clicked()"), self.connect) # QObject.connect(self.ui.disconnectPushButton, SIGNAL("clicked()"), self.disconnect) QObject.connect(self.ui.cmdLineEdit, SIGNAL("returnPressed()"), self.processCmd) QObject.connect(self.reader, SIGNAL("newData(QString)"), self.updateLog) QObject.connect(self.reader, SIGNAL("error(QString)"), self.printError) QObject.connect(self.writer, SIGNAL("error(QString)"), self.printError) def getUSBPorts(self): return glob.glob("/dev/ttyUSB*") def getSPPorts(self): return glob.glob("/dev/ttyS*") def getWinPorts(self): return ["COM1", "COM2", "COM3", "COM5"] def getSelectedPort(self): return self.ui.portsComboBox.currentText() def getSelectedBaudRate(self): return self.ui.baudRateComboBox.currentText() def refreshPorts(self): self.ui.portsComboBox.clear() self.ui.portsComboBox.addItems(sorted(self.getUSBPorts())) self.ui.portsComboBox.addItems(sorted(self.getSPPorts())) self.ui.portsComboBox.addItems(sorted(self.getWinPorts())) def connect(self): if self.connected: self.connected = False self.stopThreads() self.ui.connectPushButton.setText("connect") self.ui.connectPushButton.setDown(False) if self.ser.isOpen: self.ser.close() self.setWindowTitle("disconnected") self.ser = None else: self.ui.connectPushButton.setDown(True) self.ui.connectPushButton.setText("disconnect") self.setWindowTitle("%s:%s" % (self.getSelectedPort(), self.getSelectedBaudRate())) try: # self.ui.setWindowTitle("%s:%s" % (self.getSelectedPort(), self.getSelectedBaudRate())) self.ser = serial.Serial(str(self.getSelectedPort()), int(self.getSelectedBaudRate())) self.ser.write("\n") self.connected = True self.startReader(self.ser) except: self.ser = None self.connected = False self.printError("ERROR") def startReader(self, ser): self.reader.start(ser) def stopThreads(self): self.stopReader() self.stopWriter() def stopReader(self): if self.reader.isRunning(): self.reader.terminate() def stopWriter(self): if self.writer.isRunning(): self.writer.terminate() def printInfo(self, text): self.ui.logPlainTextEdit.appendPlainText(text) self.ui.logPlainTextEdit.moveCursor(QTextCursor.End) def printError(self, text): self.ui.logPlainTextEdit.appendPlainText(text) self.ui.logPlainTextEdit.moveCursor(QTextCursor.End) def printCmd(self, text): self.ui.logPlainTextEdit.appendPlainText("> " + text + "\n") self.ui.logPlainTextEdit.moveCursor(QTextCursor.End) def updateLog(self, text): self.ui.logPlainTextEdit.moveCursor(QTextCursor.End) # print([text]) ptext = str(text) if '\n' in ptext: ptext = '\n'.join(filter(None, ptext.splitlines())) if (len(ptext) < 4 and '->' in ptext) or "[vxWorks *]#" in ptext: ptext = '\n' + ptext + '\n' else: ptext += '\n' # if not '->' == ptext[0:1] and ptext[-1] is not '\n': # ptext += '\n' # print([ptext]) self.ui.logPlainTextEdit.insertPlainText(ptext) self.ui.logPlainTextEdit.moveCursor(QTextCursor.End) def processCmd(self): cmd = self.ui.cmdLineEdit.text() self.writer.start(self.ser, cmd) self.ui.cmdLineEdit.clear() def closeEvent(self, event): pass
class ApplicationWindow(QtWidgets.QMainWindow): def __init__(self): super(ApplicationWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self)
class QmyMainWindow(QMainWindow): def __init__(self, parent=None, flags=Qt.WindowFlags()): super().__init__(parent=parent, flags=flags) self._ui = Ui_MainWindow() self._ui.setupUi(self) self.setCentralWidget(self._ui.splitter) self.__setActionForButton() self.__createSelection() self.__Flageditable = (Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | \ Qt.ItemIsEnabled | Qt.ItemIsEditable) self.__FlagNotEditable = (Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) def __setActionForButton(self): # 为 ToolButton 按钮设置 Action self._ui.toolButton.setDefaultAction(self._ui.action_InitList) self._ui.toolButton_2.setDefaultAction(self._ui.action_ClearList) self._ui.toolButton_3.setDefaultAction(self._ui.action_Insert) self._ui.toolButton_4.setDefaultAction(self._ui.action_DeleteItem) self._ui.toolButton_5.setDefaultAction(self._ui.action_InitList) # self._ui.toolButton_6.setDefaultAction(self._ui.action_Add) self._ui.toolButton_7.setDefaultAction(self._ui.action_ClearList) self._ui.toolButton_8.setDefaultAction(self._ui.action_DeleteItem) def __createSelection(self): # 创建 ToolButton 按钮的下拉菜单 menuselection = QMenu(self) menuselection.addAction(self._ui.action_Add) menuselection.addAction(self._ui.action_ClearList) menuselection.addAction(self._ui.action_DeleteItem) # ListWidget 上方的 btnSelectItem 按钮 self._ui.toolButton_6.setPopupMode(QToolButton.MenuButtonPopup) self._ui.toolButton_6.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) self._ui.toolButton_6.setDefaultAction(self._ui.action_Add) self._ui.toolButton_6.setMenu(menuselection) toolBtn = QToolButton(self) toolBtn.setPopupMode(QToolButton.InstantPopup) toolBtn.setDefaultAction(self._ui.action_ClearList) toolBtn.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) toolBtn.setMenu(menuselection) self._ui.toolBar.addWidget(toolBtn) self._ui.toolBar.addSeparator() self._ui.toolBar.addAction(self._ui.action_Add) def on_action_Add_triggered(self): # 初始化列表 icon = QIcon(':/icon/images/724.bmp') editable = self._ui.checkBox.isChecked() if editable: Flag = self.__FlagEditable else: Flag = self.__FlagNotEditable self._ui.listWidget.clear() for i in range(10): itemStr = 'Item %d' % i aItem = QListWidgetItem() aItem.setText(itemStr) aItem.setIcon(icon) aItem.setCheckState(Qt.Checked) aItem.setFlags(Flag) self._ui.listWidget.addItem(aItem) def on_action_Insert_triggered(self): icon = QIcon(':/icon/images/724.bmp') editable = self._ui.checkBox.isChecked() if editable: Flag = self.__FlagEditable else: Flag = self.__FlagNotEditable aItem = QListWidgetItem() aItem.setText('Insert Item') aItem.setIcon(icon) aItem.setCheckState(Qt.Checked) aItem.setFlags(Flag) curRow = self._ui.listWidget.currentRow() self._ui.listWidget.insertItem(curRow, aItem) def on_action_Delete_triggered(self): row = self._ui.listWidget.currentRow() self._ui.listWidget.takeItem(row) def on_action_Clear_triggered(self): self._ui.listWidget.clear() def on_action_All_triggered(self): for i in range(self._ui.listWidget.count()): aItem = self._ui.listWidget.item(i) aItem.setCheckState(Qt.checked) def on_action_None_triggered(self): for i in range(self._ui.listWidget.count()): aItem = self._ui.listWidget.item(i) aItem.setCheckState(Qt.Unchecked) def on_action_Invs_triggered(self): for i in range(self._ui.listWidget.count()): aItem = self._ui.listWidget.item(i) if aItem.checkState() != Qt.Checked: aItem.setCheckState(Qt.checked) else: aItem.setCheckState(Qt.Unchecked) def on_listWidget_currentItemChanged(self, current, previous): strInfo = '' if current: if previous: strInfo = f'当前:{current.text()};前一项:{previous.text()}' else: strInfo = f'当前:{current.text()}' self._ui.lineEdit.setText(strInfo) def on_listWidget_customContextMenuRequested(self, pos): menuList = QMenu(self) menuList.addAction(self._ui.action_InitList) menuList.addAction(self._ui.action_Add) menuList.addAction(self._ui.action_ClearList) menuList.addAction(self._ui.action_Insert) menuList.addAction(self._ui.action_DeleteItem) menuList.exec(QCursor.pos())
class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.search = None self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setWindowTitle('The Inventory ' + settings.getVersionString()) self.connectToDatabase() # /=====================================\ # | SLOTS/SIGNALS | # buttons self.ui.btnAddItem.clicked.connect(self.itemEditor_newItem) self.ui.btnEditItem.clicked.connect(self.itemEditor_editItem) self.ui.btnDuplicateItem.clicked.connect(self.itemEditor_duplicateItem) self.ui.btnDeleteItem.clicked.connect(self.deleteItem) # itemList self.ui.itemList.itemSelectionChanged.connect(self.itemList_selectionChanged) # searching self.ui.btnSearchQuick.clicked.connect(self.search_quick) # menu self.ui.actionRecreateLists.triggered.connect(self.menuDatabase_actionRecreateLists) self.ui.actionDownloadDatabase.triggered.connect(self.menuDatabase_actionDownloadDatabase) self.ui.actionProgramVersion.triggered.connect(self.menuAbout_actionProgramVersion) # | SLOTS/SIGNALS | # \=====================================/ self.itemList_refresh() self.itemProperties_showItem(None) def resizeEvent(self,resizeEvent): self.itemList_refreshHeaders() def showEvent(self, showEvent): self.itemList_refreshHeaders() def connectToDatabase(self): self.connection = mongo() if not self.connection.connected: QMessageBox.critical(self.ui.centralwidget, "Connection to MongoDB", "Connection to database failed. Exiting application.") raise SystemExit('Connection to database failed. Exiting application.') def saveConfig(self): settings = {'itemList_nameWidth': 100, 'itemList_amountWidth': 100, 'itemList_categoryWidth': 100, 'itemList_containerWidth': 100 } file = open('config.json', 'w') json.dumps(settings, file) file.close() print 'Settings saved' ################################################################ #### itemPropertiesTable ####################################### ################################################################ def itemProperties_showItem(self, item): self.ui.itemProperties.clear() if item is not None: preparedList = [] if '_id' in item: preparedList.append(('Object ID:', str(item['_id']))) if 'created' in item: preparedList.append(('Created:', str(item['created']))) if 'modified' in item: preparedList.append(('Modified:', str(item['modified']))) if 'programVersion' in item: preparedList.append(('Program version:', settings.getVersionString(item['programVersion']))) if 'name' in item: preparedList.append(('Name:', item['name'])) if 'category' in item: preparedList.append(('Category:', item['category'])) if 'container' in item: preparedList.append(('Container:', item['container'])) if 'amount' in item: preparedList.append(('Amount:', str(item['amount']))) if 'amountUnit' in item: preparedList.append(('Amount unit:', item['amountUnit'])) if 'flags' in item: preparedList.append(('Flags:', str.join(', ', item['flags']))) if 'description' in item: preparedList.append(('Description:', item['description'])) if 'tags' in item: preparedList.append(('Tags:', str.join(', ', item['tags']))) if 'brand' in item: preparedList.append(('Brand:', item['brand'])) if 'model' in item: preparedList.append(('Model:', item['model'])) if 'version' in item: preparedList.append(('Version:', item['version'])) if 'serialNumber' in item: preparedList.append(('Serial number:', item['serialNumber'])) if 'buyDate' in item: preparedList.append(('Buy date:', str(item['buyDate']))) if 'buyPlace' in item: preparedList.append(('Buy place:', item['buyPlace'])) if 'warranty' in item: preparedList.append(('Warranty:', str(item['warranty']) + ' months')) if 'price' in item: preparedList.append(('Price:', str(item['price']) + ' zł')) if 'colors' in item: preparedList.append(('Colors:', str.join(', ', item['colors']))) if 'materials' in item: preparedList.append(('Materials:', str.join(', ', item['materials']))) if 'weight' in item: preparedList.append(('Weight:', str(item['weight']) + ' g')) if 'width' in item: preparedList.append(('Width:', str(item['width']) + ' mm')) if 'height' in item: preparedList.append(('Height:', str(item['height']) + ' mm')) if 'depth' in item: preparedList.append(('Depth:', str(item['depth']) + ' mm')) if 'radius1' in item: preparedList.append(('Radius 1:', str(item['radius1']) + ' mm')) if 'radius2' in item: preparedList.append(('Radius 2:', str(item['radius2']) + ' mm')) if 'containerLabel' in item: preparedList.append(('Container label:', item['containerLabel'])) if 'containerCategories' in item: preparedList.append(('Allowed categories:', str.join(', ', item['containerCategories']))) for prepared in preparedList: field = QtGui.QTreeWidgetItem(self.ui.itemProperties, prepared) field.setBackgroundColor(0, QtGui.QColor(255,230,192)) value = QtGui.QTreeWidgetItem(field) label = QtGui.QLabel(prepared[1]) label.setWordWrap(True) self.ui.itemProperties.setItemWidget(value, 0, label) self.ui.itemProperties.expandAll() ################################################################ #### itemList ################################################## ################################################################ def itemList_refresh(self): self.ui.itemList.clear() header = QtGui.QTreeWidgetItem(['Name', 'Amount', 'Category', 'Container']) self.ui.itemList.setHeaderItem(header) items = None if self.search is None: items = self.connection.getAllItems() print 'All items:', items.count() elif self.search[0] == 'quick': items = self.connection.searchItem_quick(self.search[1]['text'], self.search[1]['containerFlag']) print 'Found', items.count(), 'items' for item in items: name = '-=- NO NAME -=-' if 'name' in item: name = item['name'] amount = '---' if 'amount' in item and 'amountUnit' in item: amount = str(item['amount']) + ' ' + item['amountUnit'] category = '-=- NONE -=-' if 'category' in item: category = item['category'] container = '-=- NONE -=-' if 'container' in item: container = item['container'] listItem = QtGui.QTreeWidgetItem(self.ui.itemList) listItem.id = item['_id'] labelName = QtGui.QLabel(name) labelName.setWordWrap(True) labelAmount = QtGui.QLabel(amount) labelAmount.setWordWrap(True) labelCategory = QtGui.QLabel(category) labelCategory.setWordWrap(True) labelContainer = QtGui.QLabel(container) labelContainer.setWordWrap(True) self.ui.itemList.setItemWidget(listItem, 0, labelName) self.ui.itemList.setItemWidget(listItem, 1, labelAmount) self.ui.itemList.setItemWidget(listItem, 2, labelCategory) self.ui.itemList.setItemWidget(listItem, 3, labelContainer) self.itemList_refreshHeaders() def itemList_refreshHeaders(self): width = self.ui.itemList.frameGeometry().width() height = self.ui.itemList.frameGeometry().height() self.ui.itemList.setColumnWidth(0, int(width * 0.65)) self.ui.itemList.setColumnWidth(1, int(width * 0.1)) self.ui.itemList.setColumnWidth(2, int(width * 0.1)) self.ui.itemList.setColumnWidth(3, int(width * 0.1)) def itemList_getSelectedId(self): selected = self.ui.itemList.selectedItems() if selected is not None and len(selected) > 0: return selected[0].id def itemList_getSelectedItem(self): # Returns selected item. None when none is selected id = self.itemList_getSelectedId() if id is not None: return self.connection.getItemById(id) else: return None def itemList_selectionChanged(self): # Actions to do when selection was changed self.itemProperties_showItem(self.itemList_getSelectedItem()) def deleteItem(self): canDelete = False selectedItem = self.itemList_getSelectedItem() if selectedItem is not None: container = False itemCount = 0 if 'containerLabel' in selectedItem: container = True itemCount = self.connection.countItemsInContainer(selectedItem['containerLabel']) msg = QMessageBox() msg.setWindowTitle("Deleting " + selectedItem['name']) if itemCount == 0: msg.setIcon(QMessageBox.Information) msg.setText("Do you want do delete this item?") if container: msg.setInformativeText("This is active container (" + selectedItem['containerLabel'] + "), but it contains nothing.") itemText = unicode('Item to delete:') for field in selectedItem: itemText += '\n' + field + '\t' + unicode(selectedItem[field]) msg.setDetailedText(itemText) msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No) if msg.exec_() == 16384: # 16384 = Yes; 65536 = No canDelete = True else: msg.setIcon(QMessageBox.Warning) msg.setText("Cannot delete this item. It is a container with " + str(itemCount) + " items in it. Empty it before deleting.") msg.setStandardButtons(QMessageBox.Ok) msg.exec_() if canDelete: self.connection.deleteItem(selectedItem['_id']) QMessageBox.information(self.ui.centralwidget, "Deleted", "Deletion of " + selectedItem['name'] + " was successful.") self.itemList_refresh() else: print 'There is nothing selected.' ################################################################ #### itemEditor ################################################## ################################################################ def itemEditor_newItem(self): item = {} editor = ItemEditor(self, self.connection, item, 'new') result = editor.exec_() if result == 1: if self.connection.updateItem(convertToStandardTypes(item)) is None: print 'Item synchronized with database.' else: print 'ERROR WHILE SYNCHRINIZING WITH DATABASE!' self.itemList_refresh() else: print 'Aborted' def itemEditor_editItem(self): item = self.itemList_getSelectedItem() if item is not None: editor = ItemEditor(self, self.connection, item, 'edit') result = editor.exec_() if result == 1: if self.connection.updateItem(convertToStandardTypes(item)) is None: print 'Item synchronized with database.' else: print 'ERROR WHILE SYNCHRINIZING WITH DATABASE!' self.itemList_refresh() else: print 'Aborted' def itemEditor_duplicateItem(self): item = copy.deepcopy(self.itemList_getSelectedItem()) if '_id' in item: item.pop('_id') if '_id' in item: print '_id still exists!' if 'created' in item: item.pop('created') if 'modified' in item: item.pop('modified') if 'containerLabel' in item: item.pop('containerLabel') editor = ItemEditor(self, self.connection, item, 'duplicate') result = editor.exec_() if result == 1: if self.connection.updateItem(convertToStandardTypes(item)) is None: print 'Item synchronized with database.' else: print 'ERROR WHILE SYNCHRINIZING WITH DATABASE!' self.itemList_refresh() else: print 'Aborted' ################################################################ #### Search ################################################# ################################################################ def search_quick(self): search = ['quick', {'text': unicode(self.ui.searchQuickText.text())}] container = getSelectedText(self.ui.searchQuickContainers).toLower() if container == 'items and containers': search[1]['containerFlag'] = 'all' elif container == 'only items': search[1]['containerFlag'] = 'items' if container == 'only containers': search[1]['containerFlag'] = 'containers' self.search = search self.itemList_refresh() ################################################################ #### Main Menu ################################################# ################################################################ def menuDatabase_actionRecreateLists(self): self.connection.checkLists(forceRecreate = True) def menuDatabase_actionDownloadDatabase(self): fileName = QtGui.QFileDialog.getSaveFileName(self, 'Save database', '/home', '*.pickle', '*.pickle') if fileName != '': try: database = self.connection.downloadDatabase() try: f = open(fileName, 'wb') pickle.dump(database, f) f.close() QMessageBox.information(self, 'Database saved', 'Database was successfully saved to: ' + fileName) except Exception as e: QMessageBox.critical(self, "Can't save file", "Can't save to file: " + fileName + '\n\nError: ' + str(e)) except BaseException as e: QMessageBox.critical(self, "Can't download database", "Can't download database from MongoDB server!\n\nError: " + str(e)) def menuAbout_actionProgramVersion(self): QMessageBox.information(self, 'Program version', 'Current program version: ' + settings.getVersionString())
class mainWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): QtWidgets.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) setVerbosity("debug") #Button actions self.ui.pushButton_en_server.clicked.connect( self.pushButton_serverEnable_onClicked) self.ui.pushButton_en_client.clicked.connect( self.pushButton_clientEnable_onClicked) self.ui.pushButton_chart_orientation.clicked.connect( self.pushButton_chartOrientation_onClicked) self.ui.pushButton_3d_model.clicked.connect( self.pushButton_3D_Model_onClicked) self.ui.pushButton_angle_set.clicked.connect( self.pushButton_angleSetPID_onClicked) self.ui.pushButton_speed_set.clicked.connect( self.pushButton_speedSetPID_onClicked) self.ui.pushButton_angle_zero.clicked.connect( self.pushButton_angleZeroPID_onClicked) self.ui.pushButton_speed_zero.clicked.connect( self.pushButton_speedZeroPID_onClicked) self.ui.pushButton_control_set.clicked.connect( self.pushButton_controlSet_onClicked) #Initial value self.ui.doubleSpinBox_angle_kp.setValue(ANGLE_KP_CONS) self.ui.doubleSpinBox_angle_ki.setValue(ANGLE_KI_CONS) self.ui.doubleSpinBox_angle_kd.setValue(ANGLE_KD_CONS) self.ui.doubleSpinBox_angle_kp_Aggr.setValue(ANGLE_KP_AGGR) self.ui.doubleSpinBox_angle_ki_Aggr.setValue(ANGLE_KI_AGGR) self.ui.doubleSpinBox_angle_kd_Aggr.setValue(ANGLE_KD_AGGR) self.ui.doubleSpinBox_angle_setpoint.setValue(CALIBRATED_ZERO_ANGLE) self.ui.doubleSpinBox_angle_max.setValue(ANGLE_LIMIT) self.ui.doubleSpinBox_speed_kp.setValue(SPEED_KP) self.ui.doubleSpinBox_speed_ki.setValue(SPEED_KI) self.ui.doubleSpinBox_speed_kd.setValue(SPEED_KD) self.serverUDPQueue = queue.Queue(4) self.threads = [] self.worker = None self.clientUDP = None self.serverUDP = None def pushButton_serverEnable_onClicked(self): #Create and start UDP server thread port = int(self.ui.lineEdit_port_server.text()) if self.serverUDP != None and self.worker != None: self.worker.terminate() self.serverUDP.join(timeout=1) self.worker = Worker(self) self.serverUDP = UDP_ServerThread(name=SERVER_UDP_NAME, queue=self.serverUDPQueue, UDP_PORT=port) self.serverUDP.daemon = True self.threads.append(self.serverUDP) self.serverUDP.start() self.worker.start() def pushButton_clientEnable_onClicked(self): #Create and start UDP client thread ip = self.ui.lineEdit_ip_client.text() port = int(self.ui.lineEdit_port_client.text()) if self.clientUDP != None: self.clientUDP.join(timeout=1) self.clientUDP = UDP_ClientThread(name=CLIENT_UDP_NAME, UDP_IP=ip, UDP_PORT=port) self.clientUDP.daemon = True self.threads.append(self.clientUDP) self.clientUDP.start() def pushButton_chartOrientation_onClicked(self): self.plot = Plot(self) self.plot.start() def pushButton_3D_Model_onClicked(self): self.triModel = TriModel(self) self.triModel.start() def pushButton_angleSetPID_onClicked(self): angleKpCons = self.ui.doubleSpinBox_angle_kp.value() angleKiCons = self.ui.doubleSpinBox_angle_ki.value() angleKdCons = self.ui.doubleSpinBox_angle_kd.value() angleKpAggr = self.ui.doubleSpinBox_angle_kp_Aggr.value() angleKiAggr = self.ui.doubleSpinBox_angle_ki_Aggr.value() angleKdAggr = self.ui.doubleSpinBox_angle_kd_Aggr.value() angleSetpoint = self.ui.doubleSpinBox_angle_setpoint.value() angleMax = self.ui.doubleSpinBox_angle_max.value() #(module),(data1)(data2),(data3)(...)(#) msg = CMD_PID_ANGLE + "," + \ str(angleKpCons) + "," + \ str(angleKiCons) + "," + \ str(angleKdCons) + "," + \ str(angleKpAggr) + "," + \ str(angleKiAggr) + "," + \ str(angleKdAggr) + "," + \ str(angleSetpoint) + "," + \ str(angleMax) + "#" # Sending UDP packets... if (self.clientUDP != None): self.clientUDP.putMessage(msg) def pushButton_speedSetPID_onClicked(self): speedKpCons = self.ui.doubleSpinBox_speed_kp.value() speedKiCons = self.ui.doubleSpinBox_speed_ki.value() speedKdCons = self.ui.doubleSpinBox_speed_kd.value() #(module),(data1)(data2),(data3)(...)(#) msg = CMD_PID_SPEED + "," + \ str(speedKpCons) + "," + \ str(speedKiCons) + "," + \ str(speedKdCons) + "#" # Sending UDP packets... if (self.clientUDP != None): self.clientUDP.putMessage(msg) def pushButton_angleZeroPID_onClicked(self): #(module),(data1)(data2),(data3)(...)(#) msg = CMD_PID_ANGLE + "," + \ str(0) + "," + \ str(0) + "," + \ str(0) + "," + \ str(0) + "," + \ str(0) + "," + \ str(0) + "," + \ str(0) + "," + \ str(0) + "#" # Sending UDP packets... if (self.clientUDP != None): self.clientUDP.putMessage(msg) def pushButton_speedZeroPID_onClicked(self): #(module),(data1)(data2),(data3)(...)(#) msg = CMD_PID_SPEED + "," + \ str(0) + "," + \ str(0) + "," + \ str(0) + "#" # Sending UDP packets... if (self.clientUDP != None): self.clientUDP.putMessage(msg) def pushButton_controlSet_onClicked(self): enableArduino = self.ui.checkBox_en_arduino.checkState() print(enableArduino) enableCV = self.ui.checkBox_en_cv.checkState() print(enableCV) #(module),(data1)(data2),(data3)(...)(#) msg = CMD_MANAGER + "," + \ str(enableArduino) + "," + \ str(enableCV) + "#" # Sending UDP packets... if (self.clientUDP != None): self.clientUDP.putMessage(msg)
if self.ui.radioButtonOrig.isChecked(): self.pixmap = QPixmap.fromImage(self.imageOrig) elif self.ui.radioButtonR.isChecked(): self.pixmap = QPixmap.fromImage(self.imageRd) elif self.ui.radioButtonG.isChecked(): self.pixmap = QPixmap.fromImage(self.imageGd) elif self.ui.radioButtonB.isChecked(): self.pixmap = QPixmap.fromImage(self.imageBd) else: if self.ui.radioButtonOrig.isChecked(): self.pixmap = QPixmap.fromImage(self.imageOrig) elif self.ui.radioButtonR.isChecked(): self.pixmap = QPixmap.fromImage(self.imageR) elif self.ui.radioButtonG.isChecked(): self.pixmap = QPixmap.fromImage(self.imageG) elif self.ui.radioButtonB.isChecked(): self.pixmap = QPixmap.fromImage(self.imageB) self.ui.imageLabel.setPixmap(self.pixmap) if __name__ == "__main__": app = QApplication(sys.argv) window = QMainWindow() ui = Ui_MainWindow() ui.setupUi(window) eng = Engraver(ui) window.show() sys.exit(app.exec())
class MyWindow(QtWidgets.QMainWindow, Ui_MainWindow): def __init__(self): QtWidgets.QMainWindow.__init__(self) Ui_MainWindow.__init__(self) # Set MyWindow to the center of the desktop qtRectangle = self.frameGeometry() centerPoint = QDesktopWidget().availableGeometry().center() qtRectangle.moveCenter(centerPoint) self.move(qtRectangle.topLeft()) # set other functions self.ui = Ui_MainWindow() self.ui.setupUi(self) #self.ui.action_Open1.clicked.connect(self.browseFile1) #self.ui.action_Open2.clicked.connect(self.browseFile2) self.ui.btnBrowse1.clicked.connect(self.browseFile1) self.ui.btnBrowse2.clicked.connect(self.browseFile2) #self.ui.action_Close.clicked.connect(self.closeFiles) self.ui.btnExit.clicked.connect(self.exitApp) self.ui.btnProcess.clicked.connect(self.doProcess) self.ui.btnAbout.clicked.connect(self.openAbout) # Close all files def closeFiles(self): self.ui.txLog.appendPlainText('Close all files.') # Browse for files def browseFile1(self): self.ui.txLog.appendPlainText('Browse file 1.') options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog fileName, _ = QFileDialog.getOpenFileName( self, "QFileDialog.getOpenFileName()", "", "All Files (*);;Excel files (*.xlsx)", options=options) if fileName: self.ui.txFile1.setText(fileName) self.df1 = fileName self.ui.txLog.appendPlainText('File 1: ' + fileName + ' has been selected.') def browseFile2(self): self.ui.txLog.appendPlainText('Browse file 2.') options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog fileName, _ = QFileDialog.getOpenFileName( self, "QFileDialog.getOpenFileName()", "", "All Files (*);;Excel files (*.xlsx)", options=options) if fileName: self.ui.txFile2.setText(fileName) self.df2 = fileName self.ui.txLog.appendPlainText('File 2: ' + fileName + ' has been selected.') # Process the files def doProcess(self): self.ui.txLog.appendPlainText('Processing all files.') self.CalcUnivariate() # Exit application def exitApp(self): self.ui.txLog.appendPlainText('Exit application.') sys.exit() # Open form About def openAbout(self): frAbout = FrAbout() frAbout.show() # Univariate Functions def CalcUnivariate(self): self.ui.txLog.appendPlainText("Reading file " + self.df1 + " using panda library.") df1 = pd.read_excel(r'' + self.df1 + '') self.ui.txLog.appendPlainText("Reading file " + self.df2 + " using panda library.") df2 = pd.read_excel(r'' + self.df2 + '') all_df_list = [df2, df1] data = pd.concat(all_df_list) var = [] mean = [] var1 = [] mu1 = [] stdev1 = [] ucl = [] lcl = [] center = [] x = 0 variablelist = ['Y1_1', 'Y1_2', 'Y2_1', 'Y2_2', 'Y3', 'Y4'] #""" for i in variablelist: var.append(data[[i, 'subgroup']]) mean.append( var[x].groupby('subgroup').mean()) ## mean sample by subgroup var1.append(data[i]) mu1.append(stat.mean(var1[x])) ## population mean stdev1.append(stat.stdev(var1[x])) a = mu1[x] + 3 * stdev1[x] b = mu1[x] - 3 * stdev1[x] ucl.append(a) lcl.append(b) center.append(stat.mean(mean[x][i])) mean[x].plot() plt.title('X-bar Chart Variable ' + i) ucl1 = plt.axhline(ucl[x], linestyle='--', color='r', linewidth=2) ctr = plt.axhline(center[x], color='r', linewidth=2) lcl1 = plt.axhline(lcl[x], linestyle='--', color='r', linewidth=2) spec = plt.axhline(0, linestyle='--', color='y', linewidth=3) plt.show() print('UCL variable ' + i, '=', a) print('LCL variable ' + i, '=', b) x += 1
class SeptimoArte(QtGui.QWidget): """Clase principal de programa.""" columna_actor = ( (u"Nombre", 167), (u"Cumpleaños", 120), (u"Genero", 90), (u"N° Películas", 90)) columna_pelicula = ( (u"Nombre", 200), (u"Estreno", 70), (u"Director", 150), (u"Pais", 80), (u"N° Actores", 90)) def __init__(self): """Constructor principal.""" super(SeptimoArte, self).__init__() self.tipoModel = None self.ui = Ui_MainWindow() self.ui.setupUi(self) self.centerWindow() self.setModel() self.setSignals() self.show() # Signals para cargar la grilla correspondiente al cambiar de Tab self.ui.tabWidget.currentChanged.connect(self.changedTab) def centerWindow(self): """Funcion que centra la interfaz grafica en la pantalla del usuario.""" qr = self.frameGeometry() cp = QtGui.QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) def setModel(self): """Define el módelo de la grilla para trabajarla.""" self.proxyModelActor = QtGui.QSortFilterProxyModel() self.proxyModelActor.setDynamicSortFilter(True) self.ui.actoresTreeView.sortByColumn(0, QtCore.Qt.AscendingOrder) self.ui.actoresTreeView.setModel(self.proxyModelActor) self.proxyModelMovie = QtGui.QSortFilterProxyModel() self.proxyModelMovie.setDynamicSortFilter(True) self.ui.peliculasTreeView.sortByColumn(0, QtCore.Qt.AscendingOrder) self.ui.peliculasTreeView.setModel(self.proxyModelMovie) def setSourceModel(self, model): """ Actualiza constantemente el origen de los datos para siempre tenerlos al día así pudiendo buscar y mostrar solo algunos datos. Además llama a las funciones que rellenan los comboBox de filtrado y asigna el tamaño de las columnas a las grillas respectivas. Trabaja solo en una grilla a la vez, para esto reconoce en que Tab se encuentra para solamente modificar los datos de esa grilla. """ indexTab = self.ui.tabWidget.currentIndex() # Grilla de actores if indexTab is 0: self.proxyModelActor.setSourceModel(model) # Designamos los header de la grilla y sus respectivos anchos for col, h in enumerate(self.columna_actor): model.setHeaderData(col, QtCore.Qt.Horizontal, h[0]) self.ui.actoresTreeView.setColumnWidth(col, h[1]) self.ui.buscarAPeliculaComboBox.clear() self.comboBoxTabActor() # Grilla de películas else: self.proxyModelMovie.setSourceModel(model) # Designamos los header de la grilla y sus respectivos anchos for col, h in enumerate(self.columna_pelicula): model.setHeaderData(col, QtCore.Qt.Horizontal, h[0]) self.ui.peliculasTreeView.setColumnWidth(col, h[1]) self.ui.buscarPActorComboBox.clear() self.comboBoxTabPeliculas() def loadTableData(self, parent): """ Llama a los métodos respectivos para llenar ambas grillas en la app. Reconoce cual es la grilla que se quiere ver para llenarla al momento de mostrarla. Para reconocer la grilla verifica en que Tab se encuentra: Primer Tab: Actores Segundo Tab: Películas """ self.tipoModel = parent indexTab = self.ui.tabWidget.currentIndex() # Obtiene el Tab if indexTab is 0: model = self.loadActors(parent) else: model = self.loadMovies(parent) return model def changedTab(self): """ Al cambiar de Tab en la app ordena que se actualice el Tab completo al que nos trasladamos. """ self.setSourceModel(self.loadTableData(self.tipoModel)) def setSignals(self): # Signals TabActor self.ui.actoresTreeView.clicked.connect(self.infoClick) self.ui.actoresTreeView.activated.connect(self.infoClick) self.ui.buscarANombreLineEdit.textChanged.connect( self.filtrarActorNombre) self.ui.buscarAPeliculaComboBox.currentIndexChanged.connect( self.filtrarActorPorPelicula) self.ui.nuevoAButton.clicked.connect(self.nuevoActor) #Signals TabPelicula self.ui.peliculasTreeView.clicked.connect(self.infoClick) self.ui.peliculasTreeView.activated.connect(self.infoClick) self.ui.buscarPNombreLineEdit.textChanged.connect( self.filtrarPeliculaNombre) self.ui.buscarPActorComboBox.currentIndexChanged.connect( self.filtrarPeliculaPorActor) ######################################################################## #################### Estructuración del Tab Actores #################### ######################################################################## def loadActors(self, parent): actores = controller.actor() row = len(actores) model = QtGui.QStandardItemModel(row, len(self.columna_actor), parent) for i, data in enumerate(actores): row = [data[1], data[2], data[3]] for j, field in enumerate(row): index = model.index(i, j, QtCore.QModelIndex()) model.setData(index, field) return model def comboBoxTabActor(self): """ Rellena el comboBox que se ubica en el Tab Actor (principal) con todas las películas que se encuentran en la base de datos para luego utilizarlas para filtrar el contenido de la grilla. """ peliculas = controller.pelicula() self.ui.buscarAPeliculaComboBox.insertItem(0, u"Todas") for i, data in enumerate(peliculas): self.ui.buscarAPeliculaComboBox.insertItem(i + 1, data[1]) def infoClick(self): indexTab = self.ui.tabWidget.currentIndex() if indexTab is 0: # Estamos en el Tab Actores index = self.ui.actoresTreeView.currentIndex() # n° fila tabla model = self.ui.actoresTreeView.model() nombre = model.index(index.row(), 0, QtCore.QModelIndex()).data() a = controller.obtenerActor(nombre) imagenes = os.listdir("imgActor/") foto = str(a.id_actor) + ".jpg" in imagenes if foto is True: direccion = "imgActor/{}".format(str(a.id_actor) + ".jpg") else: direccion = "imgActor/{}".format(str(a.id_actor) + ".png") self.ui.actorImagenLabel.setPixmap(QtGui.QPixmap(direccion)) else: # Estamos en el Tab Películas index = self.ui.peliculasTreeView.currentIndex() # n° fila tabla model = self.ui.peliculasTreeView.model() nombre = model.index(index.row(), 0, QtCore.QModelIndex()).data() p = controller.obtenerPelicula(nombre) imagenes = os.listdir("imgPelicula/") caratula = str(p.id_pelicula) + ".jpg" in imagenes if caratula is True: direccion = "imgPelicula/{}".format(str(p.id_pelicula) + ".jpg") else: direccion = "imgPelicula/{}".format(str(p.id_pelicula) + ".png") self.ui.peliculaImagenLabel.setPixmap(QtGui.QPixmap(direccion)) self.ui.tramaPLabel.setText(p.descripcion) def filtrarActorNombre(self): self.ui.actorImagenLabel.setPixmap(QtGui.QPixmap("")) # Oculta la img self.proxyModelActor.setFilterKeyColumn(0) regExp = QtCore.QRegExp(self.ui.buscarANombreLineEdit.text(), QtCore.Qt.CaseInsensitive, QtCore.QRegExp.RegExp) self.proxyModelActor.setFilterRegExp(regExp) def filtrarActorPorPelicula(self): self.ui.actorImagenLabel.setPixmap(QtGui.QPixmap("")) index = self.ui.buscarAPeliculaComboBox.currentIndex() if (index != 0): nombre = self.ui.buscarAPeliculaComboBox.itemText(index) pelicula = controller.obtenerPelicula(nombre) # Info de la pelicula actores = controller.actoresDeLaPelicula(pelicula.id_pelicula) actoresAFiltrar = "" for i, data in enumerate(actores): row = data[0] if i == len(actores) - 1: actoresAFiltrar += row[1] else: actoresAFiltrar += row[1] + "|" if actoresAFiltrar is "": actoresAFiltrar = u"@~@" else: self.proxyModelActor.setFilterKeyColumn(0) actoresAFiltrar = u'|' actoresFiltrados = QtCore.QRegExp( actoresAFiltrar, QtCore.Qt.CaseInsensitive, QtCore.QRegExp.RegExp) self.proxyModelActor.setFilterRegExp(actoresFiltrados) def nuevoActor(self): form = FormularioPelicula() form.exec_() self.setSourceModel(self.loadTableData(self.tipoModel)) ######################################################################## ################### Estructuración del Tab Películas ################### ######################################################################## def loadMovies(self, parent): """ Carga desde la base de datos todas las peliculas y su información a la grilla del TabActores. """ peliculas = controller.pelicula() row = len(peliculas) model = QtGui.QStandardItemModel(row, len(self.columna_pelicula), parent) for i, data in enumerate(peliculas): row = [data[1], data[2], data[3], data[4]] for j, field in enumerate(row): index = model.index(i, j, QtCore.QModelIndex()) model.setData(index, field) return model def comboBoxTabPeliculas(self): """ Rellena el comboBox que se ubica en el Tab Peliculas (secundario) con todos los actores que se encuentran en la base de datos para luego utilizarlos para filtrar el contenido de la grilla. """ actores = controller.actor() self.ui.buscarPActorComboBox.insertItem(0, u"Todos") for i, data in enumerate(actores): self.ui.buscarPActorComboBox.insertItem(i + 1, data[1]) def filtrarPeliculaNombre(self): """ Filtra por nombre de la película mientras se va escribiendo en el lineEdit. """ self.ui.peliculaImagenLabel.setPixmap(QtGui.QPixmap("")) self.ui.tramaPLabel.clear() #self.ui.buscarPActorComboBox.setCurrentIndex(0) self.proxyModelMovie.setFilterKeyColumn(0) regExp = QtCore.QRegExp(self.ui.buscarPNombreLineEdit.text(), QtCore.Qt.CaseInsensitive, QtCore.QRegExp.RegExp) self.proxyModelMovie.setFilterRegExp(regExp) def filtrarPeliculaPorActor(self): """ Filtra las películas por el actor que participo en ellas luego de seleccionar dicho actor desde el comboBox en el Tab de las Películas. """ self.ui.peliculaImagenLabel.setPixmap(QtGui.QPixmap("")) self.ui.tramaPLabel.clear() #self.ui.buscarPNombreLineEdit.clear() index = self.ui.buscarPActorComboBox.currentIndex() if (index != 0): nombre = self.ui.buscarPActorComboBox.itemText(index) actor = controller.obtenerActor(nombre) # Info del Actor peliculas = controller.peliculasDelActor(actor.id_actor) peliculasAFiltrar = "" for i, data in enumerate(peliculas): row = data[0] if i == len(peliculas) - 1: peliculasAFiltrar += row[1] else: peliculasAFiltrar += row[1] + "|" if peliculasAFiltrar is "": peliculasAFiltrar = u"@~@" else: self.proxyModelMovie.setFilterKeyColumn(0) peliculasAFiltrar = u'|' peliculasFiltradas = QtCore.QRegExp( peliculasAFiltrar, QtCore.Qt.CaseInsensitive, QtCore.QRegExp.RegExp) self.proxyModelMovie.setFilterRegExp(peliculasFiltradas)
class Controller: def __init__(self): self.classes = dict() self.monthDict = dict() self.MainWindow = QtWidgets.QMainWindow() self.ui = Ui_MainWindow() self.ui.setupUi(self.MainWindow) self.ui.btn_addClass.clicked.connect(self.openNewClassID) self.ui.btn_addStudent.clicked.connect(self.openNewStudent) self.ui.btn_addMonth.clicked.connect(self.openNewMonth) self.MainWindow.show() def openNewClassID(self): self.newWindow = QtWidgets.QMainWindow() self.ui2 = Ui_AddNewClassID() self.ui2.setupUi(self.newWindow) self.ui2.btn_OK.clicked.connect(self.addNewClass) self.newWindow.show() def addNewClass(self): str = self.ui2.input_classID.text() if str not in self.classes: self.ui.box_Class.addItem(str) self.classes[str] = SchoolClass(str) self.newWindow.close() else: msg = QtWidgets.QMessageBox() msg.setWindowTitle('Warning!') msg.setIcon(QtWidgets.QMessageBox.Warning) msg.setText("This class already exists!") msg.exec() def openNewStudent(self): self.addNewStudentWindow = QtWidgets.QMainWindow() self.ui3 = Ui_AddNewStudent() self.ui3.setupUi(self.addNewStudentWindow) self.ui3.btn_OK.clicked.connect(self.addNewStudent) self.addNewStudentWindow.show() def addNewStudent(self): try: s = self.ui3.input_Name.text() classID = str(self.ui.box_Class.currentText()) self.classes[classID].inputMember(s) self.ui.listWidget.clear() for i in self.classes[classID].getMember(): self.ui.listWidget.addItem(i.__str__()) except Exception as ex: msg = QtWidgets.QMessageBox() msg.setText(ex.__str__()) msg.exec() def openNewMonth(self): self.thrWindow = QtWidgets.QMainWindow() self.ui4 = Ui_NameDays() self.ui4.setupUi(self.thrWindow) self.ui4.btn_Add.clicked.connect(self.createNewMonth) self.ui4.btn_fromFile.clicked.connect(self.openFile) self.thrWindow.show() def createNewMonth(self): try: self.newMonth = NameDaysOfMonth(int(self.ui4.input_Name.text())) if self.newMonth.getName() not in self.monthDict: self.monthDict[self.newMonth.getName()] = [] self.ui.box_Months.addItem(self.newMonth.getName()) self.ui.calendarWidget.setSelectedDate(QDate(2019,self.newMonth.getNumber(),1)) except Exception as ex: msg = QtWidgets.QMessageBox() msg.setWindowTitle('Warning!') msg.setIcon(QtWidgets.QMessageBox.Warning) msg.setText(ex.__str__()) msg.exec() def openFile(self): try: self.filename,_ = QtWidgets.QFileDialog.getOpenFileName(None,"Select file...") self.newMonth.inputNames(self.filename) self.monthDict[self.newMonth.getName()] = self.newMonth.getNames() for i in self.newMonth.getNames(): self.ui4.listWidget.addItem(i) except Exception as ex: msg = QtWidgets.QMessageBox() msg.setWindowTitle('Warning!') msg.setIcon(QtWidgets.QMessageBox.Warning) msg.setText(ex.__str__()) msg.exec()
class terminal(QMainWindow): source = Signal(object) # source of output def __init__(self, parent=None, source=None): QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.banner() # connect(fontSizeSpin, SIGNAL(valueChanged(int), textEdit, SLOT(setFontPointSize(int)); self.ui.fontSize.valueChanged.connect(self.setFontSize) # serial port self.sptimer = QTimer() self.portname = None self.serialPort = serialio.serialPort(int(self.ui.BaudRate.currentText())) # adjust ui widgets self.UiAdjust() self.listPorts() self.show() # font size adjustment if sys.platform == 'darwin': self.show() self.raise_() else: font = self.ui.textEdit.font() font.setPointSize(font.pointSize() - 3) self.ui.textEdit.setFont(font) self.ui.fontSize.setValue(font.pointSize()) self.charwidth = self.ui.textEdit.fontMetrics().width(' ')*1.1 # widget connections self.ui.PortSelect.activated.connect(self.selectPort) self.ui.BaudRate.activated.connect(self.selectRate) self.ui.BaudRate.currentIndexChanged.connect(self.selectRate) self.ui.LoopBack.stateChanged.connect(self.connectPort) # text window self.mutex = QMutex() self.ui.textEdit.setCursorWidth(8) self.ui.textEdit.installEventFilter(self) self.messages(messageQueue()) self.ui.Find.clicked.connect(self.findText) self.ui.ClearText.clicked.connect(self.clearText) self.ui.saveText.clicked.connect(self.saveText) self.textcount = 0 # capture all qt errors to terminal window def log_uncaught_exceptions(ex_cls, ex, tb): error(''.join(traceback.format_tb(tb))) error('{0}: {1}'.format(ex_cls, ex)) sys.excepthook = log_uncaught_exceptions # setup input/output self.ui.InBuffered.clicked.connect(self.buffered) self.ui.InRaw.clicked.connect(self.rawMinusEcho) self.ui.InRawEcho.clicked.connect(self.rawPlusEcho) self.ui.InHex.clicked.connect(self.rawPlusEcho) self.ui.InRaw.click() self.echo = False self.linebuffer = [] self.ui.inputIgnore.activated.connect(self.selectIgnores) self.ui.inputIgnore.setCurrentIndex(1) # ignore cr as default self.selectIgnores() self.ui.CrOut.setId(self.ui.CRnada, 0) self.ui.LfOut.setId(self.ui.LFnada, 0) self.ui.CrOut.setId(self.ui.CRCR, 13) self.ui.LfOut.setId(self.ui.LFCR, 13) self.ui.CrOut.setId(self.ui.CRLF, 10) self.ui.LfOut.setId(self.ui.LFLF, 10) self.ui.CrOut.buttonClicked.connect(self.setCr) self.ui.LfOut.buttonClicked.connect(self.setLf) self.ui.CRCR.click() self.ui.LFnada.click() self.ui.linewrap.stateChanged.connect(self.selectLinewrap) # phrases self.ui.send1.clicked.connect(self.ui.phrase1.returnPressed) self.ui.send2.clicked.connect(self.ui.phrase2.returnPressed) self.ui.send3.clicked.connect(self.ui.phrase3.returnPressed) self.ui.send4.clicked.connect(self.ui.phrase4.returnPressed) self.ui.send5.clicked.connect(self.ui.phrase5.returnPressed) self.ui.send6.clicked.connect(self.ui.phrase6.returnPressed) self.ui.send7.clicked.connect(self.ui.phrase7.returnPressed) self.ui.send8.clicked.connect(self.ui.phrase8.returnPressed) self.ui.phrase1.returnPressed.connect(self.sendPhrase1) self.ui.phrase2.returnPressed.connect(self.sendPhrase2) self.ui.phrase3.returnPressed.connect(self.sendPhrase3) self.ui.phrase4.returnPressed.connect(self.sendPhrase4) self.ui.phrase5.returnPressed.connect(self.sendPhrase5) self.ui.phrase6.returnPressed.connect(self.sendPhrase6) self.ui.phrase7.returnPressed.connect(self.sendPhrase7) self.ui.phrase8.returnPressed.connect(self.sendPhrase8) def setFontSize(self, size): font = self.ui.textEdit.font() font.setPointSize(size) self.ui.textEdit.setFont(font) def sendPhrase(self, s): s = s+'\r' for c in s: self.keyin(c) def sendPhrase1(self): self.sendPhrase(self.ui.phrase1.text()) def sendPhrase2(self): self.sendPhrase(self.ui.phrase2.text()) def sendPhrase3(self): self.sendPhrase(self.ui.phrase3.text()) def sendPhrase4(self): self.sendPhrase(self.ui.phrase4.text()) def sendPhrase5(self): self.sendPhrase(self.ui.phrase5.text()) def sendPhrase6(self): self.sendPhrase(self.ui.phrase6.text()) def sendPhrase7(self): self.sendPhrase(self.ui.phrase7.text()) def sendPhrase8(self): self.sendPhrase(self.ui.phrase8.text()) # connections # self.source.connect(self.serialPort.sink) # self.serialPort.source.connect(self.sink) # self.source = self.serialPort.sink # self.serialPort.source = self.sink def banner(self): self.setWindowTitle('Qterm 1.1') def messages(self, q): # handle messages piped in from other threads class messageThread(QThread): output = Signal(object) def __init__(self, parent, q): QThread.__init__(self) self.q = q self.parent = parent self.output.connect(self.parent.writeStyled) def run(self): while 1: try: s = self.q.get() if s: self.output.emit(s) except Empty: print 'Empty exception' pass except Exception, e: print >>sys.stderr, e traceback.print_exc(file=sys.stderr) self.mthread = messageThread(self, q) self.mthread.start()
class Application(QtWidgets.QMainWindow): def __init__(self, parent=None): super(Application, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) # enable drag and drop self.setAcceptDrops(True) # set matplotlib FigureCanvas self.fig = Figure() self.FigureCanvas = FigureCanvas(self.fig) self.ax1 = self.fig.add_subplot(1, 2, 1) self.ax1.set_axis_off() self.ax2 = self.fig.add_subplot(1, 2, 2) self.ax2.set_axis_off() self.ui.imageLayout.addWidget(self.FigureCanvas) # button self.ui.pushButton_exec.clicked.connect(self.onClick_exec) self.ui.pushButton_save.clicked.connect(self.onClick_save) def dragEnterEvent(self, e): if e.mimeData().hasFormat('text/uri-list'): e.accept() else: e.ignore() def dropEvent(self, e): # ファイルパスを取得する urls = e.mimeData().text().split("\n") self.filepath = urls[0][8:] self.ui.infoLabel.setText("file: " + self.filepath) # display image self.image = io.imread(self.filepath) self.plotImage(self.ax1, self.image, "original image") # local thresholding self.plotLocalThresholdingImage() def onClick_exec(self): self.plotLocalThresholdingImage() def plotLocalThresholdingImage(self): # local thresholding blksize = int(self.ui.spinBox_blocksize.text()) local_thresh = threshold_local(self.image, blksize) self.binimage = self.image > local_thresh # plot image self.plotImage(self.ax2, self.binimage, 'binary image') def plotImage(self, axes, image, title='image'): axes.clear() axes.set_title(title) axes.imshow(image, cmap='gray') axes.set_axis_off() # redraw self.FigureCanvas.draw() def onClick_save(self): # show file chooser savename = QtWidgets.QFileDialog.getSaveFileName( self, 'save file', os.path.dirname(self.filepath), "PNG Image (*.png)") if savename[0]: print(savename[0]) io.imsave(savename[0], self.binimage * 255)
class terminal(QMainWindow): source = Signal(object) # source of output def __init__(self, parent=None, source=None): QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.banner() # connect(fontSizeSpin, SIGNAL(valueChanged(int), textEdit, SLOT(setFontPointSize(int)); self.ui.fontSize.valueChanged.connect(self.setFontSize) # serial port self.sptimer = QTimer() self.portname = None self.serialPort = serialio.serialPort( int(self.ui.BaudRate.currentText())) # adjust ui widgets self.UiAdjust() self.listPorts() self.show() # font size adjustment if sys.platform == 'darwin': self.show() self.raise_() else: font = self.ui.textEdit.font() font.setPointSize(font.pointSize() - 3) self.ui.textEdit.setFont(font) self.ui.fontSize.setValue(font.pointSize()) self.charwidth = self.ui.textEdit.fontMetrics().width(' ') * 1.1 # widget connections self.ui.PortSelect.activated.connect(self.selectPort) self.ui.BaudRate.activated.connect(self.selectRate) self.ui.BaudRate.currentIndexChanged.connect(self.selectRate) self.ui.LoopBack.stateChanged.connect(self.connectPort) # text window self.mutex = QMutex() self.ui.textEdit.setCursorWidth(8) self.ui.textEdit.installEventFilter(self) self.messages(messageQueue()) self.ui.Find.clicked.connect(self.findText) self.ui.ClearText.clicked.connect(self.clearText) self.ui.saveText.clicked.connect(self.saveText) self.textcount = 0 # capture all qt errors to terminal window def log_uncaught_exceptions(ex_cls, ex, tb): error(''.join(traceback.format_tb(tb))) error('{0}: {1}'.format(ex_cls, ex)) sys.excepthook = log_uncaught_exceptions # setup input/output self.ui.InBuffered.clicked.connect(self.buffered) self.ui.InRaw.clicked.connect(self.rawMinusEcho) self.ui.InRawEcho.clicked.connect(self.rawPlusEcho) self.ui.InHex.clicked.connect(self.rawPlusEcho) self.ui.InRaw.click() self.echo = False self.linebuffer = [] self.ui.inputIgnore.activated.connect(self.selectIgnores) self.ui.inputIgnore.setCurrentIndex(1) # ignore cr as default self.selectIgnores() self.ui.CrOut.setId(self.ui.CRnada, 0) self.ui.LfOut.setId(self.ui.LFnada, 0) self.ui.CrOut.setId(self.ui.CRCR, 13) self.ui.LfOut.setId(self.ui.LFCR, 13) self.ui.CrOut.setId(self.ui.CRLF, 10) self.ui.LfOut.setId(self.ui.LFLF, 10) self.ui.CrOut.buttonClicked.connect(self.setCr) self.ui.LfOut.buttonClicked.connect(self.setLf) self.ui.CRCR.click() self.ui.LFnada.click() self.ui.linewrap.stateChanged.connect(self.selectLinewrap) # phrases self.ui.send1.clicked.connect(self.ui.phrase1.returnPressed) self.ui.send2.clicked.connect(self.ui.phrase2.returnPressed) self.ui.send3.clicked.connect(self.ui.phrase3.returnPressed) self.ui.send4.clicked.connect(self.ui.phrase4.returnPressed) self.ui.send5.clicked.connect(self.ui.phrase5.returnPressed) self.ui.send6.clicked.connect(self.ui.phrase6.returnPressed) self.ui.send7.clicked.connect(self.ui.phrase7.returnPressed) self.ui.send8.clicked.connect(self.ui.phrase8.returnPressed) self.ui.phrase1.returnPressed.connect(self.sendPhrase1) self.ui.phrase2.returnPressed.connect(self.sendPhrase2) self.ui.phrase3.returnPressed.connect(self.sendPhrase3) self.ui.phrase4.returnPressed.connect(self.sendPhrase4) self.ui.phrase5.returnPressed.connect(self.sendPhrase5) self.ui.phrase6.returnPressed.connect(self.sendPhrase6) self.ui.phrase7.returnPressed.connect(self.sendPhrase7) self.ui.phrase8.returnPressed.connect(self.sendPhrase8) def setFontSize(self, size): font = self.ui.textEdit.font() font.setPointSize(size) self.ui.textEdit.setFont(font) def sendPhrase(self, s): s = s + '\r' for c in s: self.keyin(c) def sendPhrase1(self): self.sendPhrase(self.ui.phrase1.text()) def sendPhrase2(self): self.sendPhrase(self.ui.phrase2.text()) def sendPhrase3(self): self.sendPhrase(self.ui.phrase3.text()) def sendPhrase4(self): self.sendPhrase(self.ui.phrase4.text()) def sendPhrase5(self): self.sendPhrase(self.ui.phrase5.text()) def sendPhrase6(self): self.sendPhrase(self.ui.phrase6.text()) def sendPhrase7(self): self.sendPhrase(self.ui.phrase7.text()) def sendPhrase8(self): self.sendPhrase(self.ui.phrase8.text()) # connections # self.source.connect(self.serialPort.sink) # self.serialPort.source.connect(self.sink) # self.source = self.serialPort.sink # self.serialPort.source = self.sink def banner(self): self.setWindowTitle('Qterm 1.1') def messages(self, q): # handle messages piped in from other threads class messageThread(QThread): output = Signal(object) def __init__(self, parent, q): QThread.__init__(self) self.q = q self.parent = parent self.output.connect(self.parent.writeStyled) def run(self): while 1: try: s = self.q.get() if s: self.output.emit(s) except Empty: print 'Empty exception' pass except Exception, e: print >> sys.stderr, e traceback.print_exc(file=sys.stderr) self.mthread = messageThread(self, q) self.mthread.start()