class MainWindow(QMainWindow):
    """ Our main window class
    """
    def __init__(self):
        QMainWindow.__init__(self)
        self.setWindowTitle("Main Window")
        self.setGeometry(300, 250, 400, 300)
        self.statusLabel = QLabel('Showing Progress')
        self.progressBar = QProgressBar()
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(100)
    
    def CreateStatusBar(self):
        self.myStatusBar = QStatusBar()
        self.progressBar.setValue(10)
        self.myStatusBar.addWidget(self.statusLabel, 1)
        self.myStatusBar.addWidget(self.progressBar, 2)
        #self.myStatusBar.showMessage('Ready', 2000)
        self.setStatusBar(self.myStatusBar)
    
    def showProgress(self):
        while(self.progressBar.value() < self.progressBar.maximum()):
            self.progressBar.setValue(self.progressBar.value() + 10)
            time.sleep(1)
        self.statusLabel.setText('Ready')
Ejemplo n.º 2
0
class MainWindow(QMainWindow):
    """ Our Main Window """
    def __init__(self):
        """ Constructor Fucntion
        """
        QMainWindow.__init__(self)
        self.setWindowTitle("Main Window")
        self.setGeometry(300, 250, 400, 300)
        self.statusLabel = QLabel('Showing Progress')
        self.progressBar = QProgressBar()
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(100)

    def createStatusBar(self):
        """ Function to create the status bar
        """
        self.myStatusBar = QStatusBar()
        self.progressBar.setValue(10)
        self.myStatusBar.addWidget(self.statusLabel, 1)
        self.myStatusBar.addWidget(self.progressBar, 2)
        self.setStatusBar(self.myStatusBar)

    def showProgress(self):
        """ Function to show progress
        """
        while(self.progressBar.value() < self.progressBar.maximum()):
            self.progressBar.setValue(self.progressBar.value() + 10)
            time.sleep(1)

        self.statusLabel.setText('Ready')
 def SetupComponents(self):
    """ Function to setup status bar, central widget, menu bar
    """
    self.myStatusBar = QStatusBar()
    self.setStatusBar(self.myStatusBar)
    self.myStatusBar.showMessage('Ready', 10000)
    self.textEdit = QTextEdit()
    self.setCentralWidget(self.textEdit)
    # self.CreateActions()
    # self.CreateMenus()
    # self.fileMenu.addAction(self.newAction)
    # self.fileMenu.addSeparator()
    # self.fileMenu.addAction(self.exitAction)
    # self.editMenu.addAction(self.copyAction)
    # self.fileMenu.addSeparator()
    # self.editMenu.addAction(self.pasteAction)
    # self.helpMenu.addAction(self.aboutAction)



    self.myStatusBar = QStatusBar()
    self.setStatusBar(self.myStatusBar)
    self.myStatusBar.showMessage('Ready', 10000)
    self.CreateActions()
    self.CreateMenus()
    self.CreateToolBar()
    self.fileMenu.addAction(self.newAction)
    self.fileMenu.addAction(self.openAction)
    self.fileMenu.addAction(self.saveAction)
    self.fileMenu.addSeparator()
    self.fileMenu.addAction(self.exitAction)
    self.editMenu.addAction(self.cutAction)
    self.editMenu.addAction(self.copyAction)
    self.editMenu.addAction(self.pasteAction)
    self.editMenu.addSeparator()
    self.editMenu.addAction(self.undoAction)
    self.editMenu.addAction(self.redoAction)
    self.editMenu.addAction(self.ss_image)

    self.editMenu.addSeparator()
    self.editMenu.addAction(self.selectAllAction)
    self.formatMenu.addAction(self.fontAction)
    self.helpMenu.addAction(self.aboutAction)
    self.helpMenu.addSeparator()
    self.helpMenu.addAction(self.aboutQtAction)
    self.mainToolBar.addAction(self.newAction)
    self.mainToolBar.addAction(self.openAction)
    self.mainToolBar.addAction(self.saveAction)
    self.mainToolBar.addSeparator()
    self.mainToolBar.addAction(self.cutAction)
    self.mainToolBar.addAction(self.copyAction)
    self.mainToolBar.addAction(self.pasteAction)
    self.mainToolBar.addSeparator()
    self.mainToolBar.addAction(self.undoAction)
    self.mainToolBar.addAction(self.redoAction)
Ejemplo n.º 4
0
class MainWindow(QMainWindow):
    """ Our Main Window """
    def __init__(self):
        """ Constructor Fucntion
        """
        QMainWindow.__init__(self)
        self.setWindowTitle("Main Window")
        self.setGeometry(300, 250, 400, 300)

    def createStatusBar(self):
        """ Function to create Status Bar
        """
        self.myStatusBar = QStatusBar()
        self.myStatusBar.showMessage('Ready', 2000)
        self.setStatusBar(self.myStatusBar)
 def CreateStatusBar(self):
     self.myStatusBar = QStatusBar()
     self.progressBar.setValue(10)
     self.myStatusBar.addWidget(self.statusLabel, 1)
     self.myStatusBar.addWidget(self.progressBar, 2)
     #self.myStatusBar.showMessage('Ready', 2000)
     self.setStatusBar(self.myStatusBar)
Ejemplo n.º 6
0
 def createStatusBar(self):
     """ Function to create the status bar
     """
     self.myStatusBar = QStatusBar()
     self.myStatusBar.showMessage('', 2000)
     self.setStatusBar(self.myStatusBar)
     """
Ejemplo n.º 7
0
    def SetupComponents(self):
        """ Function to setup status bar, central widget, menu bar
        """
        self.myStatusBar = QStatusBar()
        self.setStatusBar(self.myStatusBar)
        self.myStatusBar.showMessage('Ready', 10000)
        self.textEdit = QTextEdit()
        self.setCentralWidget(self.textEdit)

        self.createActions()
        self.createMenus()

        # Invoques toolbar creation and after that, reuses menu actions from
        # createActions() to create toolbar bottons.
        self.CreateToolBar()
        self.mainToolBar.addAction(self.newAction)
        self.mainToolBar.addSeparator()
        self.mainToolBar.addAction(self.copyAction)
        self.mainToolBar.addAction(self.pasteAction)

        self.fileMenu.addAction(self.newAction)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.exitAction)
        self.editMenu.addAction(self.copyAction)
        self.fileMenu.addSeparator()
        self.editMenu.addAction(self.pasteAction)
        self.helpMenu.addAction(self.aboutAction)
 def CreateStatusBar(self):
    """ Function to create the status bar
    """
    self.myStatusBar = QStatusBar()
    self.progressBar.setValue(10)
    self.myStatusBar.addWidget(self.statusLabel, 1)
    self.myStatusBar.addWidget(self.progressBar, 2)
    self.setStatusBar(self.myStatusBar)
Ejemplo n.º 9
0
 def __init__(self,parent=None):
     QStatusBar.__init__(self,parent)
     self.symbolic = None
     font = self.font()
     traceLogger.debug(font.pointSize())
     if os.uname()[0] == "Darwin":
         font.setPointSize(font.pointSize() - 2)
     self.setFont(font)
     self.reduceMode = QLabel()
     self.reduceMode.setFixedWidth(
         QFontMetrics(font).width(self.tr("Mode: Algebraic")))
     self.reduceMode.setFont(font)
     self.reduceTime = QLabel()
     self.reduceTime.setFont(font)
     self.reduceStatus = QLabel()
     self.reduceStatus.setFont(font)
     self.addPermanentWidget(self.reduceMode)
     self.addPermanentWidget(self.reduceTime)
     self.addWidget(self.reduceStatus)
     self.reduceStatus.setText(self.tr("Initializing ..."))
Ejemplo n.º 10
0
 def setupStatusBar(self):
     """Ajoute une barre de status"""
     self.progressBar = QProgressBar()
     self.statusLabel = QLabel('Progression ...')
     self.progressBar.setMaximum(100)
     self.progressBar.setMinimum(0)
     self.statusBar = QStatusBar()
     # # Affiche un message durant 2 sec après ouverture de l'application
     # self.statusBar.showMessage('Please Wait ...', 2000)
     self.progressBar.setValue(10)
     self.statusBar.addWidget(self.statusLabel, 1)
     self.statusBar.addWidget(self.progressBar, 2)
     self.setStatusBar(self.statusBar)
Ejemplo n.º 11
0
    def SetupComponents(self):
        """ Function to setup status bar, central widget, menu bar
        """
        self.myStatusBar = QStatusBar()
        self.setStatusBar(self.myStatusBar)
        self.myStatusBar.showMessage('Ready', 10000)
        self.textEdit = QTextEdit()
        self.setCentralWidget(self.textEdit)

        self.createActions()
        self.createMenus()

        self.fileMenu.addAction(self.newAction)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.exitAction)
        self.editMenu.addAction(self.copyAction)
        self.fileMenu.addSeparator()
        self.editMenu.addAction(self.pasteAction)
        self.helpMenu.addAction(self.aboutAction)
Ejemplo n.º 12
0
    def __init__(self, datta):
        QMainWindow.__init__(self)
        self.setWindowTitle('Project Parser')
        appIcon = QIcon('search.png')
        self.setWindowIcon(appIcon)
        self.viewPortBL = QDesktopWidget().availableGeometry().topLeft()
        self.viewPortTR = QDesktopWidget().availableGeometry().bottomRight()
        self.margin = int(QDesktopWidget().availableGeometry().width()*0.1/2)
        self.shirina = QDesktopWidget().availableGeometry().width() - self.margin*2
        self.visota = QDesktopWidget().availableGeometry().height() - self.margin*2
        self.setGeometry(self.viewPortBL.x() + self.margin, self.viewPortBL.y() + self.margin,
                         self.shirina, self.visota)
        # statusbar
        self.myStatusBar = QStatusBar()
        self.setStatusBar(self.myStatusBar)
        
        #lower long layout
        self.lowerLong = QFrame()
        self.detailsLabel = QLabel()
        self.skillsLabel = QLabel()
        self.urlLabel = QLabel()
        self.locationLabel = QLabel()
        self.skillsLabel.setText('skills')
        self.detailsLabel.setWordWrap(True)
        self.la = QVBoxLayout()
        self.la.addWidget(self.detailsLabel)
        self.la.addWidget(self.skillsLabel)
        self.la.addWidget(self.urlLabel)
        self.la.addWidget(self.locationLabel)
        self.lowerLong.setLayout(self.la)

        # table
        self.source_model = MyTableModel(self, datta, ['Id', 'Date', 'Title'])
        self.proxy_model = myTableProxy(self)
        self.proxy_model.setSourceModel(self.source_model)
        self.proxy_model.setDynamicSortFilter(True)
        self.table_view = QTableView()
        self.table_view.setModel(self.proxy_model)
        self.table_view.setAlternatingRowColors(True)
        self.table_view.resizeColumnsToContents()
        self.table_view.resizeRowsToContents()
        self.table_view.horizontalHeader().setStretchLastSection(True)
        self.table_view.setSortingEnabled(True)
        self.table_view.sortByColumn(2, Qt.AscendingOrder)

        # events
        self.selection = self.table_view.selectionModel()
        self.selection.selectionChanged.connect(self.handleSelectionChanged)
        #DO NOT use CreateIndex() method, use index()
        index = self.proxy_model.index(0,0)
        self.selection.select(index, QItemSelectionModel.Select)
        
        self.upperLong = self.table_view  

        # right side widgets
        self.right = QFrame()
        self.la1 = QVBoxLayout()
        self.btnDownload = QPushButton('Download data')
        self.btnDownload.clicked.connect(self.download)
        self.myButton = QPushButton('Show Skillls')
        self.myButton.clicked.connect(self.showAllSkills)
        self.btnSearchByWord = QPushButton('Search by word(s)')
        self.btnSearchByWord.clicked.connect(self.onSearchByWord)
        self.btnResetFilter= QPushButton('Discard Filter')
        self.btnResetFilter.clicked.connect(self.discardFilter)
        self.btnCopyURL = QPushButton('URL to Clipboard')
        self.btnCopyURL.clicked.connect(self.copyToClipboard)
        self.btnExit = QPushButton('Exit')
        self.btnExit.clicked.connect(lambda: sys.exit())
        self.dateTimeStamp = QLabel()
        self.la1.addWidget(self.btnDownload)
        self.la1.addSpacing(10)
        self.la1.addWidget(self.myButton)
        self.la1.addSpacing(10)
        self.la1.addWidget(self.btnSearchByWord)
        self.la1.addSpacing(10)
        self.la1.addWidget(self.btnResetFilter)
        self.la1.addSpacing(10)
        self.la1.addWidget(self.btnCopyURL)
        self.la1.addSpacing(70)
        self.la1.addWidget(self.btnExit)
        self.la1.addStretch(stretch=0)
        self.la1.addWidget(self.dateTimeStamp)
        self.right.setLayout(self.la1)
        self.right.setFrameShape(QFrame.StyledPanel)

        # splitters
        self.horiSplit = QSplitter(Qt.Vertical)
        self.horiSplit.addWidget(self.upperLong)
        self.horiSplit.addWidget(self.lowerLong)
        self.horiSplit.setSizes([self.visota/2, self.visota/2])
        self.vertiSplit = QSplitter(Qt.Horizontal)
        self.vertiSplit.addWidget(self.horiSplit)
        self.vertiSplit.addWidget(self.right)
        self.vertiSplit.setSizes([self.shirina*3/4, self.shirina*1/4])
        self.setCentralWidget(self.vertiSplit)
        
        self.settings = QSettings('elance.ini', QSettings.IniFormat)
        self.settings.beginGroup('DATE_STAMP')
        self.dateTimeStamp.setText('Data actuality: %s' % self.settings.value('date/time'))
        self.settings.endGroup()
        self.statusText = ''
Ejemplo n.º 13
0
Archivo: gui.py Proyecto: tinavas/FSERP
class Gui():
    """main gui class"""
    def __init__(self):
        self.mainwindow = QMainWindow()
        settings.get_settings()
        self.access = tuple(settings.access.items())
        self.progress = QProgressDialog("Setting up modules...", "cancel", 0,
                                        7, self.mainwindow)
        self.progress.setWindowTitle(
            QApplication.translate("MainWindow", str(settings.company), None,
                                   QApplication.UnicodeUTF8))

    def setup(self):
        """initializes the uio of the erp client"""
        self.progress.setFixedWidth(1000)
        self.progress.setCancelButton(None)
        # self.progress.setWindowModality(Qt.WindowModal)
        self.progress.setValue(1)
        self.mainwindow.setObjectName("MainWindow")
        self.mainwindow.resize(832, 668)
        self.mainwindow.setStyleSheet(
            "QToolBar{\n"
            "background: qlineargradient(x1:0, y1:0, x2:1, y2:1,\n"
            "stop:0 rgba(0,0,0),stop:1 rgb(162, 162, 162, 162));\n"
            "border: 0px;\n"
            "}\n"
            "QToolBar > QWidget{\n"
            "color:white;\n"
            "}\n"
            "QToolBar > QWidget:hover {\n"
            "background:transparent;\n"
            " }\n"
            "QToolBar > QWidget:checked {\n"
            "background:transparent;\n"
            " }\n"
            "#MainWindow{\n"
            "background: qlineargradient(x1:0, y1:0, x2:1, y2:1,\n"
            "stop:0 rgba(0,0,0),stop:1 rgb(162, 162, 162, 162));\n"
            "border: 0px;\n"
            "}\n"
            "")
        self.centralWidget = QWidget(self.mainwindow)
        self.centralWidget.setObjectName("centralWidget")
        self.gridLayout_2 = QGridLayout(self.centralWidget)
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.stackedWidget = QStackedWidget(self.centralWidget)
        self.stackedWidget.setStyleSheet("")
        self.stackedWidget.setObjectName("stackedWidget")
        self.shortcut = NewShortcut()
        scroll = QScrollArea()
        scroll.setWidget(self.shortcut.shortcut_setting)
        self.stackedWidget.addWidget(self.shortcut.shortcut_setting)
        self.home_page = QWidget()
        self.home_page.setObjectName("home_page")
        self.gridLayout = QGridLayout(self.home_page)
        self.gridLayout.setObjectName("gridLayout")
        self.billing_frame_2 = QFrame(self.home_page)
        self.billing_frame_2.setStyleSheet(
            "background-image:url(:/images/billing_frame.png);\n"
            "background-repeat: no-repeat;\n"
            "background-position: center;\n"
            "background-color:#6CBED2;")
        self.billing_frame_2.setFrameShape(QFrame.StyledPanel)
        self.billing_frame_2.setFrameShadow(QFrame.Raised)
        self.billing_frame_2.setObjectName("billing_frame_2")
        self.verticalLayout_4 = QVBoxLayout(self.billing_frame_2)
        self.verticalLayout_4.setObjectName("verticalLayout_4")
        spacerItem = QSpacerItem(20, 217, QSizePolicy.Minimum,
                                 QSizePolicy.Expanding)
        self.verticalLayout_4.addItem(spacerItem)
        self.label_10 = QLabel(self.billing_frame_2)
        self.label_10.setStyleSheet("background:transparent;")
        self.label_10.setObjectName("label_10")
        self.verticalLayout_4.addWidget(self.label_10)
        self.gridLayout.addWidget(self.billing_frame_2, 0, 1, 1, 1)
        self.employee_frame_3 = QFrame(self.home_page)
        self.employee_frame_3.setStyleSheet(
            "background-image:url(:/images/employee_frame.png);\n"
            "background-repeat: no-repeat;\n"
            "background-position: center;\n"
            "background-color:#0099CC;")
        self.employee_frame_3.setFrameShape(QFrame.StyledPanel)
        self.employee_frame_3.setFrameShadow(QFrame.Raised)
        self.employee_frame_3.setObjectName("employee_frame_3")
        self.verticalLayout_5 = QVBoxLayout(self.employee_frame_3)
        self.verticalLayout_5.setObjectName("verticalLayout_5")
        spacerItem1 = QSpacerItem(20, 217, QSizePolicy.Minimum,
                                  QSizePolicy.Expanding)
        self.verticalLayout_5.addItem(spacerItem1)
        self.label_11 = QLabel(self.employee_frame_3)
        self.label_11.setStyleSheet("background:transparent;")
        self.label_11.setObjectName("label_11")
        self.verticalLayout_5.addWidget(self.label_11)
        self.gridLayout.addWidget(self.employee_frame_3, 0, 2, 1, 1)
        self.menu_frame_4 = QFrame(self.home_page)
        self.menu_frame_4.setStyleSheet(
            "background-image:url(:/images/menu_frame.png);\n"
            "background-repeat: no-repeat;\n"
            "background-position: center;\n"
            "background-color:#297ACC;")
        self.menu_frame_4.setFrameShape(QFrame.StyledPanel)
        self.menu_frame_4.setFrameShadow(QFrame.Raised)
        self.menu_frame_4.setObjectName("menu_frame_4")
        self.verticalLayout_3 = QVBoxLayout(self.menu_frame_4)
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        spacerItem2 = QSpacerItem(20, 216, QSizePolicy.Minimum,
                                  QSizePolicy.Expanding)
        self.verticalLayout_3.addItem(spacerItem2)
        self.label_12 = QLabel(self.menu_frame_4)
        self.label_12.setStyleSheet("background:transparent;")
        self.label_12.setObjectName("label_12")
        self.verticalLayout_3.addWidget(self.label_12)
        self.gridLayout.addWidget(self.menu_frame_4, 1, 0, 1, 1)
        self.report_frame_5 = QFrame(self.home_page)
        self.report_frame_5.setStyleSheet(
            "background-image:url(:/images/report_frame.png);\n"
            "background-repeat: no-repeat;\n"
            "background-position: center;\n"
            "background-color:#006BB2;")
        self.report_frame_5.setFrameShape(QFrame.StyledPanel)
        self.report_frame_5.setFrameShadow(QFrame.Raised)
        self.report_frame_5.setObjectName("report_frame_5")
        self.verticalLayout_6 = QVBoxLayout(self.report_frame_5)
        self.verticalLayout_6.setObjectName("verticalLayout_6")
        spacerItem3 = QSpacerItem(20, 216, QSizePolicy.Minimum,
                                  QSizePolicy.Expanding)
        self.verticalLayout_6.addItem(spacerItem3)
        self.label_13 = QLabel(self.report_frame_5)
        self.label_13.setStyleSheet("background:transparent;")
        self.label_13.setObjectName("label_13")
        self.verticalLayout_6.addWidget(self.label_13)
        self.gridLayout.addWidget(self.report_frame_5, 1, 1, 1, 1)
        self.waste_frame_6 = QFrame(self.home_page)
        self.waste_frame_6.setStyleSheet(
            "background-image:url(:/images/waste_frame.png);\n"
            "background-repeat: no-repeat;\n"
            "background-position: center;\n"
            "background-color:#003D7A;")
        self.waste_frame_6.setFrameShape(QFrame.StyledPanel)
        self.waste_frame_6.setFrameShadow(QFrame.Raised)
        self.waste_frame_6.setObjectName("waste_frame_6")
        self.verticalLayout_7 = QVBoxLayout(self.waste_frame_6)
        self.verticalLayout_7.setObjectName("verticalLayout_7")
        spacerItem4 = QSpacerItem(20, 216, QSizePolicy.Minimum,
                                  QSizePolicy.Expanding)
        self.verticalLayout_7.addItem(spacerItem4)
        self.label_14 = QLabel(self.waste_frame_6)
        self.label_14.setStyleSheet("background:transparent;")
        self.label_14.setObjectName("label_14")
        self.verticalLayout_7.addWidget(self.label_14)
        self.gridLayout.addWidget(self.waste_frame_6, 1, 2, 1, 1)
        self.inventory_frame_1 = QFrame(self.home_page)
        self.inventory_frame_1.setStyleSheet(
            "background-image:url(:/images/inventory_frame.png);\n"
            "background-repeat: no-repeat;\n"
            "background-position: center;\n"
            "background-color:#ADEBFF;")
        self.inventory_frame_1.setFrameShape(QFrame.StyledPanel)
        self.inventory_frame_1.setFrameShadow(QFrame.Raised)
        self.inventory_frame_1.setObjectName("inventory_frame_1")
        self.verticalLayout_2 = QVBoxLayout(self.inventory_frame_1)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        spacerItem5 = QSpacerItem(20, 217, QSizePolicy.Minimum,
                                  QSizePolicy.Expanding)
        self.verticalLayout_2.addItem(spacerItem5)
        self.label_9 = QLabel(self.inventory_frame_1)
        self.label_9.setStyleSheet("background:transparent;")
        self.label_9.setObjectName("label_9")
        self.verticalLayout_2.addWidget(self.label_9)
        self.gridLayout.addWidget(self.inventory_frame_1, 0, 0, 1, 1)
        self.stackedWidget.addWidget(self.home_page)
        self.detail_page = QWidget()
        self.detail_page.setObjectName("detail_page")
        self.horizontalLayout_2 = QHBoxLayout(self.detail_page)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.main_tabWidget = QTabWidget(self.detail_page)
        self.main_tabWidget.setAutoFillBackground(False)
        self.main_tabWidget.setStyleSheet("")
        self.main_tabWidget.setTabPosition(QTabWidget.West)
        self.main_tabWidget.setIconSize(QSize(60, 60))
        self.main_tabWidget.setElideMode(Qt.ElideNone)
        self.main_tabWidget.setObjectName("main_tabWidget")
        ##initializes the tabs
        self.add_tabs()
        self.main_tabWidget.setFocusPolicy(Qt.StrongFocus)
        self.main_tabWidget.focusInEvent = self.change_focus
        self.main_tabWidget.currentChanged.connect(self.change_focus)
        self.stackedWidget.currentChanged.connect(self.change_focus)
        ######
        self.horizontalLayout_2.addWidget(self.main_tabWidget)
        self.stackedWidget.addWidget(self.detail_page)
        if ('Admin', True) in self.access:
            self.stackedWidget.addWidget(Admin(self.mainwindow))
        notification = NotificationTab()
        tab = notification.notificationTab_tab_4
        tab.custom_class_object = notification  # class_object is used to access the api through the
        self.stackedWidget.addWidget(tab)
        self.gridLayout_2.addWidget(self.stackedWidget, 0, 0, 1, 1)
        self.mainwindow.setCentralWidget(self.centralWidget)
        self.menuBar = QMenuBar(self.mainwindow)
        self.menuBar.setGeometry(QRect(0, 0, 832, 29))
        self.menuBar.setObjectName("menuBar")
        self.mainwindow.setMenuBar(self.menuBar)
        self.mainToolBar = QToolBar(self.mainwindow)
        self.mainToolBar.setLayoutDirection(Qt.RightToLeft)
        self.mainToolBar.setStyleSheet("")
        self.mainToolBar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        self.mainToolBar.setObjectName("mainToolBar")
        self.mainwindow.addToolBar(Qt.TopToolBarArea, self.mainToolBar)
        self.statusBar = QStatusBar(self.mainwindow)
        self.statusBar.setObjectName("statusBar")
        self.mainwindow.setStatusBar(self.statusBar)
        self.toolBar = QToolBar(self.mainwindow)
        self.toolBar.setLayoutDirection(Qt.RightToLeft)
        self.toolBar.setStyleSheet("")
        self.toolBar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        self.toolBar.setObjectName("toolBar")
        self.mainwindow.addToolBar(Qt.TopToolBarArea, self.toolBar)
        self.actionNotification = QAction(self.mainwindow)
        self.actionNotification.setCheckable(True)
        self.actionNotification.setChecked(False)
        self.actionNotification.setEnabled(True)
        icon6 = QIcon()
        icon6.addPixmap(QPixmap(":/images/notification.png"), QIcon.Normal,
                        QIcon.Off)
        self.actionNotification.setIcon(icon6)
        self.actionNotification.setAutoRepeat(True)
        self.actionNotification.setVisible(True)
        self.actionNotification.setIconVisibleInMenu(False)
        self.actionNotification.setObjectName("actionNotification")
        self.actionNotification
        self.actionAdmin = QAction(self.mainwindow)
        # self.actionAdmin.setCheckable(True)
        icon7 = QIcon()
        icon7.addPixmap(QPixmap(":/images/admin.png"), QIcon.Normal, QIcon.Off)
        self.actionAdmin.setIcon(icon7)
        self.actionAdmin.setObjectName("actionAdmin")
        self.actionRefresh = QAction(self.mainwindow)
        icon8 = QIcon()
        icon8.addPixmap(QPixmap(":/images/refresh.png"), QIcon.Normal,
                        QIcon.Off)
        self.actionRefresh.setIcon(icon8)
        self.actionRefresh.setObjectName("actionRefresh")
        self.actionHome = QAction(self.mainwindow)
        # self.actionHome.setCheckable(True)
        icon9 = QIcon()
        icon9.addPixmap(QPixmap(":/images/home.png"), QIcon.Normal, QIcon.Off)
        self.actionHome.setIcon(icon9)
        self.actionHome.setObjectName("actionHome")
        self.actionSettings = QAction(self.mainwindow)
        icon10 = QIcon()
        icon10.addPixmap(QPixmap(":/images/settings.png"), QIcon.Normal,
                         QIcon.Off)
        self.actionSettings.setIcon(icon10)
        self.actionSettings.setObjectName("actionRefresh")
        self.toolBar.addAction(self.actionNotification)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.actionAdmin)
        if ('Admin', True) in self.access:
            self.toolBar.addSeparator()
        else:
            self.actionAdmin.setVisible(False)
        self.toolBar.addAction(self.actionHome)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.actionRefresh)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.actionSettings)
        ##retranslates
        self.mainwindow.setWindowTitle(
            QApplication.translate("MainWindow", settings.company, None,
                                   QApplication.UnicodeUTF8))
        self.label_10.setText(
            QApplication.translate(
                "MainWindow",
                "<html><head/><body><p align=\"center\">BILLING</p></body></html>",
                None, QApplication.UnicodeUTF8))
        self.label_11.setText(
            QApplication.translate(
                "MainWindow",
                "<html><head/><body><p align=\"center\">EMPLOYEE</p></body></html>",
                None, QApplication.UnicodeUTF8))
        self.label_12.setText(
            QApplication.translate(
                "MainWindow",
                "<html><head/><body><p align=\"center\">MENU</p></body></html>",
                None, QApplication.UnicodeUTF8))
        self.label_13.setText(
            QApplication.translate(
                "MainWindow",
                "<html><head/><body><p align=\"center\">REPORT</p></body></html>",
                None, QApplication.UnicodeUTF8))
        self.label_14.setText(
            QApplication.translate(
                "MainWindow",
                "<html><head/><body><p align=\"center\">WASTE</p></body></html>",
                None, QApplication.UnicodeUTF8))
        self.label_9.setText(
            QApplication.translate(
                "MainWindow",
                "<html><head/><body><p align=\"center\">INVENTORY</p></body></html>",
                None, QApplication.UnicodeUTF8))
        self.inventory_frame_1.setToolTip(
            QApplication.translate("MainWindow", "Go to the Inventory Tab",
                                   None, QApplication.UnicodeUTF8))
        self.billing_frame_2.setToolTip(
            QApplication.translate("MainWindow", "Go to the Billing Tab", None,
                                   QApplication.UnicodeUTF8))
        self.employee_frame_3.setToolTip(
            QApplication.translate("MainWindow", "Go to the Employee Tab",
                                   None, QApplication.UnicodeUTF8))
        self.menu_frame_4.setToolTip(
            QApplication.translate("MainWindow", "Go to the Menu Tab", None,
                                   QApplication.UnicodeUTF8))
        self.report_frame_5.setToolTip(
            QApplication.translate("MainWindow", "Go to the Report Tab", None,
                                   QApplication.UnicodeUTF8))
        self.waste_frame_6.setToolTip(
            QApplication.translate("MainWindow", "Go to the Waste Tab", None,
                                   QApplication.UnicodeUTF8))
        self.toolBar.setWindowTitle(
            QApplication.translate("MainWindow", "toolBar", None,
                                   QApplication.UnicodeUTF8))
        self.actionNotification.setText("&&Notification")
        # QApplication.translate("MainWindow", "&Notification", None, QApplication.UnicodeUTF8))
        self.actionNotification.setToolTip(
            QApplication.translate("MainWindow",
                                   "Click to see new notifications", None,
                                   QApplication.UnicodeUTF8))
        # self.actionNotification.setShortcut(
        # QApplication.translate("MainWindow", "Ctrl+Shift+N", None, QApplication.UnicodeUTF8))
        self.actionAdmin.setText('&&Admin')
        # QApplication.translate("MainWindow", "Admin", None, QApplication.UnicodeUTF8))
        self.actionAdmin.setToolTip(
            QApplication.translate("MainWindow",
                                   "Click to go to admin interface", None,
                                   QApplication.UnicodeUTF8))
        # self.actionAdmin.setShortcut(
        # QApplication.translate("MainWindow", "Ctrl+Shift+A", None, QApplication.UnicodeUTF8))
        self.actionRefresh.setText("&&Refresh")
        # QApplication.translate("MainWindow", "Refresh", None, QApplication.UnicodeUTF8))
        self.actionRefresh.setToolTip(
            QApplication.translate("MainWindow",
                                   "refreshes the data from the server", None,
                                   QApplication.UnicodeUTF8))
        # self.actionRefresh.setShortcut(
        # QApplication.translate("MainWindow", "Ctrl+Shift+R", None, QApplication.UnicodeUTF8))
        self.actionHome.setText('&&Home')
        # QApplication.translate("MainWindow", "Home", None, QApplication.UnicodeUTF8))
        self.actionHome.setToolTip(
            QApplication.translate("MainWindow", "Go back to the home screen",
                                   None, QApplication.UnicodeUTF8))
        self.actionSettings.setText('&&Settings')
        # QApplication.translate("MainWindow", "Settings", None, QApplication.UnicodeUTF8))
        self.actionSettings.setToolTip(
            QApplication.translate("MainWindow", "Go to the settings panel",
                                   None, QApplication.UnicodeUTF8))
        # self.actionHome.setShortcut(
        #     QApplication.translate("MainWindow", "Ctrl+Shift+H", None, QApplication.UnicodeUTF8))
        self.stackedWidget.setCurrentIndex(1)
        self.main_tabWidget.setCurrentIndex(0)

        self.ob = self.main_tabWidget.tabBar()
        # self.add_tool_tip(self.ob) todo avoided due to segmentation fault error, left for future fixes
        self.tb = EventHandlerForTabBar()
        self.ob.installEventFilter(self.tb)

        QMetaObject.connectSlotsByName(self.mainwindow)

    def add_tabs(self):
        """
        adds new tabs
        """
        global logger
        if ('Inventory', True) in self.access:
            logger.info('initiating Inventory')
            icon = QIcon()
            icon.addPixmap(QPixmap(":/images/inventory.png"), QIcon.Normal,
                           QIcon.Off)
            from inventory.inventory import Inventory

            inventory = Inventory()
            # inventory.inventory_tab_1.setToolTip("Inventory Section")
            self.main_tabWidget.addTab(inventory.inventory_tab_1, icon, "")
            inventory.inventory_detail_tabWidget.setCurrentIndex(0)
        else:
            self.inventory_frame_1.setVisible(False)
        self.progress.setLabelText('Inventory Done....')
        self.progress.setValue(2)

        if ('Billing', True) in self.access:
            logger.info('initiating Billing')
            icon1 = QIcon()
            icon1.addPixmap(QPixmap(":/images/billing.png"), QIcon.Normal,
                            QIcon.Off)
            from billing.billing import Billing

            bill = Billing()
            # bill.billing_tab_2.setToolTip("Billing Section")
            self.main_tabWidget.addTab(bill.billing_tab_2, icon1, "")
            bill.billing_detail_tabWidget.setCurrentIndex(0)
        else:
            self.billing_frame_2.setVisible(False)
        self.progress.setLabelText('Billing Done...')
        self.progress.setValue(3)

        if ('Employee', True) in self.access:
            logger.info('initiating Employee')
            icon2 = QIcon()
            icon2.addPixmap(QPixmap(":/images/employee.png"), QIcon.Normal,
                            QIcon.Off)
            from employee.employee import Employee

            employee = Employee()
            # employee.employee_tab_3.setToolTip("Employee Section")
            self.main_tabWidget.addTab(employee.employee_tab_3, icon2, "")
            employee.employee_detail_tabWidget.setCurrentIndex(0)
        else:
            self.employee_frame_3.setVisible(False)
        self.progress.setLabelText('Employee Done...')
        self.progress.setValue(4)

        if ('Menu', True) in self.access:
            logger.info('initiating Menu')
            icon3 = QIcon()
            icon3.addPixmap(QPixmap(":/images/menu.png"), QIcon.Normal,
                            QIcon.Off)
            from menu.menu import Menu

            menu = Menu()
            # menu.menu_tab_4.setToolTip("Menu Section")
            self.main_tabWidget.addTab(menu.menu_tab_4, icon3, "")
            menu.menu_detail_tabWidget.setCurrentIndex(0)
        else:
            self.menu_frame_4.setVisible(False)
        self.progress.setLabelText('Menu Done....')
        self.progress.setValue(5)

        if ('Report', True) in self.access:
            logger.info('initiating Report')
            icon4 = QIcon()
            icon4.addPixmap(QPixmap(":/images/report.png"), QIcon.Normal,
                            QIcon.Off)
            from report.report import Report

            report = Report()
            # report.report_tab_5.setToolTip("Report Section")
            self.main_tabWidget.addTab(report.report_tab_5, icon4, "")
            report.report_detail_tabWidget.setCurrentIndex(0)
        else:
            self.report_frame_5.setVisible(False)
        self.progress.setLabelText('Report Done....')
        self.progress.setValue(6)

        if ('Waste', True) in self.access:
            logger.info('initiating Waste')
            icon5 = QIcon()
            icon5.addPixmap(QPixmap(":/images/waste.png"), QIcon.Normal,
                            QIcon.Off)
            from waste.waste import Waste

            waste = Waste()
            # waste.waste_tab_6.setToolTip("Waste Section")
            self.main_tabWidget.addTab(waste.waste_tab_6, icon5, "")
            waste.waste_detail_tabWidget.setCurrentIndex(0)
        else:
            self.waste_frame_6.setVisible(False)
        self.progress.setLabelText('Waste Done....')
        self.progress.setValue(7)

    def change_focus(self, event=None):
        """
        focus method to set focus to a tab to initialize the corresponding events of the tab
        """
        wid = self.main_tabWidget.currentWidget()
        if wid:
            if wid.isVisible():
                # print wid.objectName()
                # print '1y'
                wid.setFocus()

    def add_tool_tip(
        self, ob
    ):  # todo not working causing segmentation fault, avoided calling this function
        """
        method to add tool tip to the tabs
        :param ob: Tab bar
        """
        obj = ob
        count = obj.count()
        hardcode = {
            0: 'Inventory Section',
            1: "Billing Section",
            2: "Employee Section",
            3: "Menu Section",
            4: "Report Section",
            5: "Waste Section"
        }
        for i in range(count):
            obj.setTabToolTip(i, hardcode[i])
Ejemplo n.º 14
0
class MainWindow(QMainWindow):
    """ Create the Application Main Window CLass
    """
    def __init__(self):
        """ Constructor FUnction
        """
        QMainWindow.__init__(self)
        self.setWindowTitle("Application Title Here")
        self.setGeometry(300, 250, 400, 300)

    def SetupComponents(self):
        """ Setting the Central Widget
        """
        self.myStatusBar = QStatusBar()
        self.setStatusBar(self.myStatusBar)
        self.myStatusBar.showMessage('Ready', 10000)
        self.textEdit = QTextEdit()
        self.setCentralWidget(self.textEdit)
        self.CreateActions()
        self.CreateMenus()
        self.fileMenu.addAction(self.newAction)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.exitAction)
        self.editMenu.addAction(self.copyAction)
        self.editMenu.addSeparator()
        self.editMenu.addAction(self.pasteAction)
        self.helpMenu.addAction(self.aboutAction)
        self.helpMenu.addSeparator()
        self.helpMenu.addAction(self.aboutCopyrightAction)
        self.CreateToolBar()
        self.mainToolBar.addAction(self.newAction)
        self.mainToolBar.addSeparator()
        self.mainToolBar.addAction(self.copyAction)
        self.mainToolBar.addAction(self.pasteAction)

    # Slots called when the action menus are triggered
    def newFile(self):
       self.textEdit.setText('')

    def exitFile(self):
        self.close()

    def aboutHelp(self):
        QMessageBox.about(self, "About Simple Text Editor",
                          "This example demonstrates the use "
                          "of Menu Bar")
    def aboutCopyright(self):
        QMessageBox.about(self, "About Simple Text Editor",
                          "This example demonstrates the use "
                          "of Copyright Bar")

    def CreateActions(self):
        """ Function to create actions for menus
        """
        self.newAction = QAction(QIcon('new.png'), '&New',
                                  self, shortcut=QKeySequence.New,
                                  statusTip="Create a New File",
                                  triggered=self.newFile)
        self.exitAction = QAction(QIcon('exit.png'), 'E&xit',
                                  self, shortcut="Ctrl+Q",
                                  statusTip="Exit the Application",
                                  triggered=self.exitFile)
        self.copyAction = QAction(QIcon('copy.png'), 'C&opy',
                                  self, shortcut="Ctrl+C",
                                  statusTip="Copy",
                                  triggered=self.textEdit.copy)
        self.pasteAction = QAction(QIcon('paste.png'), '&Paste',
                                   self, shortcut="Ctrl+V",
                                   statusTip="Paste",
                                   triggered=self.textEdit.paste)
        self.aboutAction = QAction(QIcon('about.png'), 'A&bout',
                                   self, statusTip="Displays info about text editor",
                                   triggered=self.aboutHelp)
        self.aboutCopyrightAction = QAction(QIcon('about.png'), '&Copyright',
                                   self, statusTip="Displays info about Copyright",
                                   triggered=self.aboutCopyright)

    def CreateMenus(self):
        """ Function to create actual menu bar
        """
        self.fileMenu = self.menuBar().addMenu("&File")
        self.editMenu = self.menuBar().addMenu("&Edit")
        self.viewMenu = self.menuBar().addMenu("&View")
        self.helpMenu = self.menuBar().addMenu("&Help")

    def CreateToolBar(self):
        """ Function to create tool bar
        """
        self.mainToolBar = self.addToolBar('Main')
Ejemplo n.º 15
0
 def __init__(self, parent=None):
     super(Truss, self).__init__(parent)        
     self.resize(800, 600)
     self.filename  = None
     self.filetuple = None
     self.dirty = False  # Refers to Data Page only.
     centralwidget = QWidget(self)
     gridLayout = QGridLayout(centralwidget)
     self.tabWidget = QTabWidget(centralwidget)
     self.tab = QWidget()
     font = QFont()
     font.setFamily("Courier 10 Pitch")
     font.setPointSize(12)
     self.tab.setFont(font)
     gridLayout_3 = QGridLayout(self.tab)
     self.plainTextEdit = QPlainTextEdit(self.tab)
     gridLayout_3.addWidget(self.plainTextEdit, 0, 0, 1, 1)
     self.tabWidget.addTab(self.tab, "")
     self.tab_2 = QWidget()
     self.tab_2.setFont(font)
     gridLayout_2 = QGridLayout(self.tab_2)
     self.plainTextEdit_2 = QPlainTextEdit(self.tab_2)
     gridLayout_2.addWidget(self.plainTextEdit_2, 0, 0, 1, 1)
     self.tabWidget.addTab(self.tab_2, "")
     gridLayout.addWidget(self.tabWidget, 0, 0, 1, 1)
     self.setCentralWidget(centralwidget)
     menubar = QMenuBar(self)
     menubar.setGeometry(QRect(0, 0, 800, 29))
     menu_File = QMenu(menubar)
     self.menu_Solve = QMenu(menubar)
     self.menu_Help = QMenu(menubar)
     self.setMenuBar(menubar)
     self.statusbar = QStatusBar(self)
     self.setStatusBar(self.statusbar)
     self.action_New = QAction(self)
     self.actionSave_As = QAction(self)
     self.action_Save = QAction(self)
     self.action_Open = QAction(self)
     self.action_Quit = QAction(self)
     self.action_About = QAction(self)
     self.actionShow_CCPL = QAction(self)
     self.action_Solve = QAction(self)
     self.action_CCPL = QAction(self)
     self.action_Help = QAction(self)
     menu_File.addAction(self.action_New)
     menu_File.addAction(self.action_Open)
     menu_File.addAction(self.actionSave_As)
     menu_File.addAction(self.action_Save)
     menu_File.addSeparator()
     menu_File.addAction(self.action_Quit)
     self.menu_Solve.addAction(self.action_Solve)
     self.menu_Help.addAction(self.action_About)
     self.menu_Help.addAction(self.action_CCPL)
     self.menu_Help.addAction(self.action_Help)
     menubar.addAction(menu_File.menuAction())
     menubar.addAction(self.menu_Solve.menuAction())
     menubar.addAction(self.menu_Help.menuAction())        
     self.setWindowTitle("Main Window")
     self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab),\
                                "Data Page")
     self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2),\
                                "Solution Page")        
     menu_File.setTitle("&File")        
     self.menu_Solve.setTitle("&Solve")
     self.menu_Help.setTitle("&Help")
     self.tabWidget.setCurrentIndex(0)
     self.action_New.setText("&New") 
     self.action_Open.setText("&Open")       
     self.actionSave_As.setText("Save &As")
     self.action_Save.setText("&Save")
     self.action_Quit.setText("&Quit")        
     self.action_Solve.setText("&Solve")
     self.action_About.setText("&About")
     self.action_CCPL.setText("&CCPL")
     self.action_Help.setText("&Help")
     self.action_Quit.triggered.connect(self.close)
     allToolBar = self.addToolBar("AllToolBar") 
     allToolBar.setObjectName("AllToolBar") 
     self.addActions(allToolBar, (self.action_Open, self.actionSave_As,\
                     self.action_Save, self.action_Solve,\
                     self.action_Quit ))
     self.action_New.triggered.connect(self.fileNew)
     self.action_Open.triggered.connect(self.fileOpen)
     self.actionSave_As.triggered.connect(self.fileSaveAs)
     self.action_Save.triggered.connect(self.fileSave)
     self.action_Solve.triggered.connect(self.trussSolve)
     self.action_About.triggered.connect(self.aboutBox)
     self.action_CCPL.triggered.connect(self.displayCCPL)
     self.action_Help.triggered.connect(self.help)
     self.plainTextEdit.textChanged.connect(self.setDirty)
     self.action_New = self.editAction(self.action_New, None,\
                         'ctrl+N', 'filenew', 'New File.')   
     self.action_Open = self.editAction(self.action_Open, None, 
                         'ctrl+O', 'fileopen', 'Open File.')
     self.actionSave_As = self.editAction(self.actionSave_As,\
                         None, 'ctrl+A', 'filesaveas',\
                         'Save and Name File.')
     self.action_Save = self.editAction(self.action_Save, None, 
                         'ctrl+S', 'filesave', 'Save File.')
     self.action_Solve = self.editAction(self.action_Solve, None, 
                         'ctrl+L', 'solve', 'Solve Structure.')                                   
     self.action_About = self.editAction(self.action_About, None, 
                         'ctrl+B', 'about','Pop About Box.')                                  
     self.action_CCPL = self.editAction(self.action_CCPL, None, 
                         'ctrl+G', 'licence', 'Show Licence') 
     self.action_Help = self.editAction(self.action_Help, None, 
                         'ctrl+H', 'help', 'Show Help Page.')
     self.action_Quit =  self.editAction(self.action_Quit, None, 
                         'ctrl+Q', 'quit', 'Quit the program.')                                           
     self.plainTextEdit_2.setReadOnly(True)
Ejemplo n.º 16
0
def main():
    """Execute QDarkStyle example."""
    parser = argparse.ArgumentParser(description=__doc__,
                                     formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('--qt_from', default='qtpy',
                        choices=['pyqt', 'pyqt5', 'pyside','pyside2', 'qtpy', 'pyqtgraph'],
                        help="Choose which wrapper/framework is to be used to run the example.", type=str)
    parser.add_argument('--no_dark', action='store_true',
                        help="Exihibts the original  window (without qdarkstyle).")
    parser.add_argument('--test', action='store_true',
                        help="Auto close window after 2s.")
    parser.add_argument('--reset', action='store_true',
                        help="Reset GUI settings (position, size).")
    parser.add_argument('--screenshots', action='store_true',
                        help="Generate screenshots.")


    # parsing arguments from command line
    args = parser.parse_args()

    # set log for debug
    logging.basicConfig(level=logging.DEBUG)

    # to avoid problems when testing without screen
    if args.test:
        os.environ['QT_QPA_PLATFORM']='offscreen'

    if args.qt_from == 'pyside':
        # using PySide wrapper
        from PySide.QtGui import QApplication, QMainWindow, QDockWidget, QStatusBar, QLabel, QPushButton
        from PySide.QtCore import QTimer, Qt, QSettings, QByteArray, QPoint, QSize
        # import examples UI according to wrapper
        from ui.mw_menus_pyside_ui import Ui_MainWindow as ui_main

        from ui.dw_buttons_pyside_ui import Ui_DockWidget as ui_buttons
        from ui.dw_displays_pyside_ui import Ui_DockWidget as ui_displays
        from ui.dw_inputs_fields_pyside_ui import Ui_DockWidget as ui_inputs_fields
        from ui.dw_inputs_no_fields_pyside_ui import Ui_DockWidget as ui_inputs_no_fields

        from ui.dw_widgets_pyside_ui import Ui_DockWidget as ui_widgets
        from ui.dw_views_pyside_ui import Ui_DockWidget as ui_views
        from ui.dw_containers_tabs_pyside_ui import Ui_DockWidget as ui_containers_tabs
        from ui.dw_containers_no_tabs_pyside_ui import Ui_DockWidget as ui_containers_no_tabs

        # Getting style
        style_method = qdarkstyle.load_stylesheet_pyside

    elif args.qt_from == 'pyqt':
        # using PyQt4 wrapper
        from PyQt4.QtGui import QApplication, QMainWindow, QDockWidget, QStatusBar, QLabel, QPushButton
        from PyQt4.QtCore import QTimer, Qt, QSettings, QByteArray, QPoint, QSize
        # import examples UI according to wrapper
        from ui.mw_menus_pyqt_ui import Ui_MainWindow as ui_main

        from ui.dw_buttons_pyqt_ui import Ui_DockWidget as ui_buttons
        from ui.dw_displays_pyqt_ui import Ui_DockWidget as ui_displays
        from ui.dw_inputs_fields_pyqt_ui import Ui_DockWidget as ui_inputs_fields
        from ui.dw_inputs_no_fields_pyqt_ui import Ui_DockWidget as ui_inputs_no_fields

        from ui.dw_widgets_pyqt_ui import Ui_DockWidget as ui_widgets
        from ui.dw_views_pyqt_ui import Ui_DockWidget as ui_views
        from ui.dw_containers_tabs_pyqt_ui import Ui_DockWidget as ui_containers_tabs
        from ui.dw_containers_no_tabs_pyqt_ui import Ui_DockWidget as ui_containers_no_tabs

        # Getting style
        style_method = qdarkstyle.load_stylesheet_pyqt

    elif args.qt_from == 'pyqt5':
        # using PyQt5 wrapper
        from PyQt5.QtWidgets import QApplication, QMainWindow, QDockWidget, QStatusBar, QLabel, QPushButton
        from PyQt5.QtCore import QTimer, Qt, QSettings, QByteArray, QPoint, QSize
        # import examples UI according to wrapper
        from ui.mw_menus_pyqt5_ui import Ui_MainWindow as ui_main

        from ui.dw_buttons_pyqt5_ui import Ui_DockWidget as ui_buttons
        from ui.dw_displays_pyqt5_ui import Ui_DockWidget as ui_displays
        from ui.dw_inputs_fields_pyqt5_ui import Ui_DockWidget as ui_inputs_fields
        from ui.dw_inputs_no_fields_pyqt5_ui import Ui_DockWidget as ui_inputs_no_fields

        from ui.dw_widgets_pyqt5_ui import Ui_DockWidget as ui_widgets
        from ui.dw_views_pyqt5_ui import Ui_DockWidget as ui_views
        from ui.dw_containers_tabs_pyqt5_ui import Ui_DockWidget as ui_containers_tabs
        from ui.dw_containers_no_tabs_pyqt5_ui import Ui_DockWidget as ui_containers_no_tabs

        # Getting style
        style_method = qdarkstyle.load_stylesheet_pyqt5

    elif args.qt_from == 'pyside2':
        # using PyQt5 wrapper
        from PySide2.QtWidgets import QApplication, QMainWindow, QDockWidget, QStatusBar, QLabel, QPushButton
        from PySide2.QtCore import QTimer, Qt, QSettings, QByteArray, QPoint, QSize
        # import examples UI according to wrapper
        from ui.mw_menus_pyside2_ui import Ui_MainWindow as ui_main

        from ui.dw_buttons_pyside2_ui import Ui_DockWidget as ui_buttons
        from ui.dw_displays_pyside2_ui import Ui_DockWidget as ui_displays
        from ui.dw_inputs_fields_pyside2_ui import Ui_DockWidget as ui_inputs_fields
        from ui.dw_inputs_no_fields_pyside2_ui import Ui_DockWidget as ui_inputs_no_fields

        from ui.dw_widgets_pyside2_ui import Ui_DockWidget as ui_widgets
        from ui.dw_views_pyside2_ui import Ui_DockWidget as ui_views
        from ui.dw_containers_tabs_pyside2_ui import Ui_DockWidget as ui_containers_tabs
        from ui.dw_containers_no_tabs_pyside2_ui import Ui_DockWidget as ui_containers_no_tabs

        # Getting style
        style_method = qdarkstyle.load_stylesheet_pyside2

    elif args.qt_from == 'qtpy':
        # using QtPy API
        from qtpy.QtWidgets import QApplication, QMainWindow, QDockWidget, QStatusBar, QLabel, QPushButton
        from qtpy.QtCore import QTimer, Qt, QSettings, QByteArray, QPoint, QSize
        # import examples UI according to wrapper
        from ui.mw_menus_qtpy_ui import Ui_MainWindow as ui_main

        from ui.dw_buttons_qtpy_ui import Ui_DockWidget as ui_buttons
        from ui.dw_displays_qtpy_ui import Ui_DockWidget as ui_displays
        from ui.dw_inputs_fields_qtpy_ui import Ui_DockWidget as ui_inputs_fields
        from ui.dw_inputs_no_fields_qtpy_ui import Ui_DockWidget as ui_inputs_no_fields

        from ui.dw_widgets_qtpy_ui import Ui_DockWidget as ui_widgets
        from ui.dw_views_qtpy_ui import Ui_DockWidget as ui_views
        from ui.dw_containers_tabs_qtpy_ui import Ui_DockWidget as ui_containers_tabs
        from ui.dw_containers_no_tabs_qtpy_ui import Ui_DockWidget as ui_containers_no_tabs

        # Getting style
        style_method = qdarkstyle.load_stylesheet_from_environment

    elif args.qt_from == 'pyqtgraph':
        # using PyQtGraph API
        from pyqtgraph.Qt.QtGui import QApplication, QMainWindow, QDockWidget, QStatusBar, QLabel, QPushButton
        from pyqtgraph.Qt.QtCore import QTimer, Qt, QSettings, QByteArray, QPoint, QSize
        #from pyqtgraph.Qt import QtGui, QtCore
        # import examples UI according to wrapper
        from ui.mw_menus_pyqtgraph_ui import Ui_MainWindow as ui_main
        from ui.dw_buttons_pyqtgraph_ui import Ui_DockWidget as ui_buttons
        from ui.dw_displays_pyqtgraph_ui import Ui_DockWidget as ui_displays
        from ui.dw_inputs_fields_pyqtgraph_ui import Ui_DockWidget as ui_inputs_fields
        from ui.dw_inputs_no_fields_pyqtgraph_ui import Ui_DockWidget as ui_inputs_no_fields
        from ui.dw_widgets_pyqtgraph_ui import Ui_DockWidget as ui_widgets
        from ui.dw_views_pyqtgraph_ui import Ui_DockWidget as ui_views
        from ui.dw_containers_tabs_pyqtgraph_ui import Ui_DockWidget as ui_containers_tabs
        from ui.dw_containers_no_tabs_pyqtgraph_ui import Ui_DockWidget as ui_containers_no_tabs

        # Getting style
        style_method = lambda: qdarkstyle.load_stylesheet_from_environment(is_pyqtgraph=True)

    if args.no_dark:
        style = ''

    def write_settings(window):
        """Get window settings and write it into a file."""
        settings = QSettings('QDarkStyle', 'QDarkStyle Example')
        settings.setValue('pos', window.pos())
        settings.setValue('size', window.size())
        settings.setValue('state', window.saveState())

    def read_settings(window, reset=False):
        """Read and set window settings from a file."""
        settings = QSettings('QDarkStyle', 'QDarkStyle Example')
        if args.qt_from == 'pyside' or args.qt_from == 'pyside2':
            pos = settings.value('pos', window.pos())
            size = settings.value('size', window.size())
            state = settings.value('state', window.saveState())
        else:
            pos = settings.value('pos', window.pos(), type='QPoint')
            size = settings.value('size', window.size(), type='QSize')
            state = settings.value('state', window.saveState(), type='QByteArray')

        if not reset:
            window.restoreState(state)
            window.resize(size)
            window.move(pos)

    # create the application
    app = QApplication(sys.argv)
    app.setOrganizationName('QDarkStyle')
    app.setApplicationName('QDarkStyle Example')

    # setup stylesheet
    style = style_method()
    app.setStyleSheet(style)

    # create main window
    window = QMainWindow()
    window.setObjectName('mainwindow')
    ui = ui_main()
    ui.setupUi(window)
    window.setWindowTitle("QDarkStyle v." + qdarkstyle.__version__)

    # create docks for buttons
    dw_buttons = QDockWidget()
    dw_buttons.setObjectName('buttons')
    ui_buttons = ui_buttons()
    ui_buttons.setupUi(dw_buttons)
    window.addDockWidget(Qt.RightDockWidgetArea, dw_buttons)

    # create docks for buttons
    dw_displays = QDockWidget()
    dw_displays.setObjectName('displays')
    ui_displays = ui_displays()
    ui_displays.setupUi(dw_displays)
    window.addDockWidget(Qt.RightDockWidgetArea, dw_displays)

    # create docks for inputs - no fields
    dw_inputs_no_fields = QDockWidget()
    dw_inputs_no_fields.setObjectName('inputs_no_fields')
    ui_inputs_no_fields = ui_inputs_no_fields()
    ui_inputs_no_fields.setupUi(dw_inputs_no_fields)
    window.addDockWidget(Qt.RightDockWidgetArea, dw_inputs_no_fields)

    # create docks for inputs - fields
    dw_inputs_fields = QDockWidget()
    dw_inputs_fields.setObjectName('_fields')
    ui_inputs_fields = ui_inputs_fields()
    ui_inputs_fields.setupUi(dw_inputs_fields)
    window.addDockWidget(Qt.RightDockWidgetArea, dw_inputs_fields)

    # create docks for widgets
    dw_widgets = QDockWidget()
    dw_widgets.setObjectName('widgets')
    ui_widgets = ui_widgets()
    ui_widgets.setupUi(dw_widgets)
    window.addDockWidget(Qt.LeftDockWidgetArea, dw_widgets)

    # create docks for views
    dw_views = QDockWidget()
    dw_views.setObjectName('views')
    ui_views = ui_views()
    ui_views.setupUi(dw_views)
    window.addDockWidget(Qt.LeftDockWidgetArea, dw_views)

    # create docks for containers - no tabs
    dw_containers_no_tabs = QDockWidget()
    dw_containers_no_tabs.setObjectName('containers_no_tabs')
    ui_containers_no_tabs = ui_containers_no_tabs()
    ui_containers_no_tabs.setupUi(dw_containers_no_tabs)
    window.addDockWidget(Qt.LeftDockWidgetArea, dw_containers_no_tabs)

    # create docks for containters - tabs
    dw_containers_tabs = QDockWidget()
    dw_containers_tabs.setObjectName('containers')
    ui_containers_tabs = ui_containers_tabs()
    ui_containers_tabs.setupUi(dw_containers_tabs)
    window.addDockWidget(Qt.LeftDockWidgetArea, dw_containers_tabs)

    # tabify right docks
    window.tabifyDockWidget(dw_buttons, dw_displays)
    window.tabifyDockWidget(dw_displays, dw_inputs_fields)
    window.tabifyDockWidget(dw_inputs_fields, dw_inputs_no_fields)

    # tabify right docks
    window.tabifyDockWidget(dw_containers_no_tabs, dw_containers_tabs)
    window.tabifyDockWidget(dw_containers_tabs, dw_widgets)
    window.tabifyDockWidget(dw_widgets, dw_views)

    # issues #9120, #9121 on Spyder
    qstatusbar = QStatusBar()
    qstatusbar.addWidget(QLabel('Issue Spyder #9120, #9121 - background not matching.'))
    qstatusbar.addWidget(QPushButton('OK'))
    window.setStatusBar(qstatusbar)

    # auto quit after 2s when testing on travis-ci
    if args.test:
        QTimer.singleShot(2000, app.exit)

    # run
    read_settings(window, args.reset)
    window.showMaximized()

    # Save screenshots for differents displays and quit
    if args.screenshots:
        window.showFullScreen()
        QTimer.singleShot(1000, lambda: create_screenshots(app, window, not args.no_dark))

    app.exec_()
    write_settings(window)
Ejemplo n.º 17
0
class MainWindow(QMainWindow):
    """ Our Main Window class
    """
    def __init__(self):
        """ Constructor Function
        """
        QMainWindow.__init__(self)
        self.setWindowTitle("A Simple Text Editor")
        self.setWindowIcon(QIcon('appicon.png'))
        self.setGeometry(300, 250, 400, 300)

    def SetupComponents(self):
        """ Function to setup status bar, central widget, menu bar
        """
        self.myStatusBar = QStatusBar()
        self.setStatusBar(self.myStatusBar)
        self.myStatusBar.showMessage('Ready', 10000)
        self.textEdit = QTextEdit()
        self.setCentralWidget(self.textEdit)
        self.CreateActions()
        self.CreateMenus()
        self.fileMenu.addAction(self.newAction)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.exitAction)
        self.editMenu.addAction(self.copyAction)
        self.fileMenu.addSeparator()
        self.editMenu.addAction(self.pasteAction)
        self.helpMenu.addAction(self.aboutAction)

    # slots called when the menu actions are triggered
    def newFile(self):
        self.textEdit.setText('')

    def exitFile(self):
        self.close()

    def aboutHelp(self):
        QMessageBox.about(
            self, "about a simple Text Editor",
            "This example demostrates the sue "
            " of the menu bar")

    def CreateActions(self):
        """ Function to create actions for menus
        """
        self.newAction = QAction(QIcon('new.png'),
                                 '&New',
                                 self,
                                 shortcut=QKeySequence.New,
                                 statusTip="Create a New File",
                                 triggered=self.newFile)
        self.copyAction = QAction(QIcon('copy.png'),
                                  'C&opy',
                                  self,
                                  shortcut="Ctrl+C",
                                  statusTip="Copy",
                                  triggered=self.textEdit.copy)
        self.pasteAction = QAction(QIcon('paste.png'),
                                   '&Paste',
                                   self,
                                   shortcut="Ctrl+V",
                                   statusTip="Paste",
                                   triggered=self.textEdit.paste)
        self.aboutAction = QAction(QIcon('about.png'),
                                   'A&bout',
                                   self,
                                   statusTip="Displays info about text editor",
                                   triggered=self.aboutHelp)

        self.exitAction = QAction(QIcon('exit.png'),
                                  'E&xit',
                                  self,
                                  shortcut="Ctrl+Q",
                                  statusTip="Exit the Application",
                                  triggered=self.exitFile)

    # Actual menu bar item creation
    def CreateMenus(self):
        """ Function to create actual menu bar
        """
        self.fileMenu = self.menuBar().addMenu("&File")
        self.editMenu = self.menuBar().addMenu("&Edit")
        self.helpMenu = self.menuBar().addMenu("&Help")
class SampleWindow(QMainWindow):
 """ Our main window class
 """
 def __init__(self,fileName=None):
    """ Constructor Function
    """
    # QWidget.__init__(self)
    # self.setWindowTitle("Icon Sample")
    # self.setGeometry(300, 300, 200, 150)
    QMainWindow.__init__(self)
    self.setWindowTitle("Icon Sample")
    self.setGeometry(300, 300, 200, 150)
    QToolTip.setFont(QFont("Decorative", 8, QFont.Bold))
    self.setToolTip('Our Main Window')
    self.icon='C:\Users\Hamed\Documents\soheil sites image\imageedit__9411602959.gif'
    self.textEdit = QTextEdit()
    self.setCentralWidget(self.textEdit)
    self.fileName = None
    self.filters = "Text files (*.txt)"

    openFile = QAction(QIcon('open.png'), 'Open', self)
    openFile.setShortcut('Ctrl+O')
    openFile.setStatusTip('Open new File')
    openFile.triggered.connect(self.showDialog)
    menubar = self.menuBar()
    # fileMenu = menubar.addMenu('&File')
    # fileMenu.addAction(openFile)
    self.setGeometry(300, 300, 350, 300)
    self.setWindowTitle('Example - File Dialog')

    # self.myNameLE = QLineEdit(self)
    # self.myAgeLE = QLineEdit(self)
    # self.myChoiceLE = QLineEdit(self)

    self.statusLabel = QLabel('Showing Progress')
    self.progressBar = QProgressBar()
    self.progressBar.setMinimum(0)
    self.progressBar.setMaximum(100)
##################@@@@@@@@@@@@@@2
    self.threads = []

    self.addWorker(MyWorkerThread(1))
    self.addWorker(MyWorkerThread(2))
#######################@@@@@@@@@@@@@
    self.show()
##########################@@@@@@@@@@
 def addWorker(self, worker):
        worker.message.connect(self.printMessage, QtCore.Qt.QueuedConnection)
        # connect the finished signal to method so that we are notified
        worker.finished.connect(self.workersFinished)
        self.threads.append(worker)

 def startWorkers(self):
        for worker in self.threads:
            worker.start()
            # no wait, no finished. you start the threads and leave.

 def workersFinished(self):
        if all(worker.isFinished() for worker in self.threads):
            # wait until all the threads finished
            QtCore.QCoreApplication.instance().quit()

 @QtCore.Slot(str)
 def printMessage(self, text):
        sys.stdout.write(text+'\n')
        sys.stdout.flush()
################################

 def openAbout(self):
    aboutDialog = QtGui.QDialog(self)
    # aboutUi = about.About_Dialog()
    # aboutUi.setupUi(aboutDialog)
    aboutDialog.show()

 def newwindow(self):
        # w = W1()
        # w.show()
        # self.hide()
        # form = Form()
        # form.show()

        w2 = chooseoption.Form1(self)
        w2.show()
        import webbrowser
        your_swf_url='E:\soheil\web_site_root\ieee\all_functions\linux server\python GUI\Double_angle_off.swf'
        webbrowser.open(your_swf_url)
        # self.wid = QWidget()
        # self.wid.resize(250, 150)
        # self.wid.setWindowTitle('NewWindow')
        # self.wid.show()
        # self.actionAbout.triggered.connect(self.openAbout)
 def retranslateUi(self, Dialog):
    Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8))
    self.aboutLbl.setText(QtGui.QApplication.translate("Dialog", "Mailer version 0.0.1 by .....", None, QtGui.QApplication.UnicodeUTF8))

 def showNameDialog(self):
    text, ok = QInputDialog.getText(self, 'Input Text Dialog',
    'Enter your name:')
    if ok:
        self.myNameLE.setText(str(text))

 def showDialog(self):
    fileName, _ = QFileDialog.getOpenFileName(self, "Open Text Files", "c:/", "Text files(*.txt)")
    try:
        contents = open(fileName, 'r')
        with contents:
            data = contents.read()
            self.textEdit.setText(data)
    except:
        pass

 def CreateStatusBar(self):
    """ Function to create the status bar
    """
    self.myStatusBar = QStatusBar()
    self.progressBar.setValue(10)
    self.myStatusBar.addWidget(self.statusLabel, 1)
    self.myStatusBar.addWidget(self.progressBar, 2)
    self.setStatusBar(self.myStatusBar)
 def ShowProgress(self):
    """ Function to show progress
    """
    import time
    while(self.progressBar.value() < self.progressBar.maximum()):
        self.progressBar.setValue(self.progressBar.value() + 10)
        # time.sleep(1)
    self.statusLabel.setText('Ready')
 def SetupComponents(self):
    """ Function to setup status bar, central widget, menu bar
    """
    self.myStatusBar = QStatusBar()
    self.setStatusBar(self.myStatusBar)
    self.myStatusBar.showMessage('Ready', 10000)
    self.textEdit = QTextEdit()
    self.setCentralWidget(self.textEdit)
    # self.CreateActions()
    # self.CreateMenus()
    # self.fileMenu.addAction(self.newAction)
    # self.fileMenu.addSeparator()
    # self.fileMenu.addAction(self.exitAction)
    # self.editMenu.addAction(self.copyAction)
    # self.fileMenu.addSeparator()
    # self.editMenu.addAction(self.pasteAction)
    # self.helpMenu.addAction(self.aboutAction)



    self.myStatusBar = QStatusBar()
    self.setStatusBar(self.myStatusBar)
    self.myStatusBar.showMessage('Ready', 10000)
    self.CreateActions()
    self.CreateMenus()
    self.CreateToolBar()
    self.fileMenu.addAction(self.newAction)
    self.fileMenu.addAction(self.openAction)
    self.fileMenu.addAction(self.saveAction)
    self.fileMenu.addSeparator()
    self.fileMenu.addAction(self.exitAction)
    self.editMenu.addAction(self.cutAction)
    self.editMenu.addAction(self.copyAction)
    self.editMenu.addAction(self.pasteAction)
    self.editMenu.addSeparator()
    self.editMenu.addAction(self.undoAction)
    self.editMenu.addAction(self.redoAction)
    self.editMenu.addAction(self.ss_image)

    self.editMenu.addSeparator()
    self.editMenu.addAction(self.selectAllAction)
    self.formatMenu.addAction(self.fontAction)
    self.helpMenu.addAction(self.aboutAction)
    self.helpMenu.addSeparator()
    self.helpMenu.addAction(self.aboutQtAction)
    self.mainToolBar.addAction(self.newAction)
    self.mainToolBar.addAction(self.openAction)
    self.mainToolBar.addAction(self.saveAction)
    self.mainToolBar.addSeparator()
    self.mainToolBar.addAction(self.cutAction)
    self.mainToolBar.addAction(self.copyAction)
    self.mainToolBar.addAction(self.pasteAction)
    self.mainToolBar.addSeparator()
    self.mainToolBar.addAction(self.undoAction)
    self.mainToolBar.addAction(self.redoAction)


 def openFile(self):
    self.fileName, self.filterName =QFileDialog.getOpenFileName(self)
    try:
        self.textEdit.setText(open(self.fileName).read())
    except:
        pass
    # Slots called when the menu actions are triggered
 def newFile(self):
    self.textEdit.setText('')
 def exitFile(self):
    self.close()
 def aboutHelp(self):
    QMessageBox.about(self, "About Simple Text Editor",
    "This example demonstrates the use "
    "of Menu Bar")

 def fontChange(self):
    (font, ok) = QFontDialog.getFont(QFont("Helvetica [Cronyx]", 10), self)
    if ok:
        self.textEdit.setCurrentFont(font)

 def saveFile(self):
    if self.fileName == None or self.fileName == '':
        self.fileName, self.filterName = QFileDialog.getSaveFileName(self, \
        filter=self.filters)
    if(self.fileName != ''):
        file = open(self.fileName, 'w')
        file.write(self.textEdit.toPlainText())
        self.statusBar().showMessage("File saved", 2000)
 def image_ss(self):
    from PySide import QtGui, QtCore

    import wxpython_flash_Simple_working
    hbox = QtGui.QHBoxLayout(self)
    pixmap = QtGui.QPixmap('C:\Users\Hamed\Pictures\LED\led.jpg')

    lbl = QtGui.QLabel(self)
    lbl.setPixmap(pixmap)

    hbox.addWidget(lbl)
    self.setLayout(hbox)

    self.setGeometry(300, 300, 280, 170)
    self.setWindowTitle('Red Rock')

    self.show()


    # from PIL import Image
    # from PySide.QtGui import QImage, QImageReader, QLabel, QPixmap, QApplication
    #
    # im = Image.open('C:\Users\Hamed\Documents\soheil sites image\imageedit__9411602959.gif')
    # data = im.tostring('raw')
    #
    ##app = QApplication([])
    ## image = QImage(data);
    # image = QImage(data, im.size[0], im.size[1], QImage.Format_ARGB32)
    # pix = QPixmap.fromImage(image)
    # lbl = QLabel()
    # lbl.setPixmap(pix)
    # lbl.show()
 def image_ss_main(self):
    from PySide import QtGui, QtCore
    hbox = QtGui.QHBoxLayout(self)
    pixmap = QtGui.QPixmap('C:\Users\Hamed\Pictures\LED\led.jpg')

    lbl = QtGui.QLabel(self)
    lbl.setPixmap(pixmap)

    hbox.addWidget(lbl)
    self.setLayout(hbox)

    self.setGeometry(300, 300, 280, 170)
    self.setWindowTitle('Red Rock')

    self.show()


    # from PIL import Image
    # from PySide.QtGui import QImage, QImageReader, QLabel, QPixmap, QApplication
    #
    # im = Image.open('C:\Users\Hamed\Documents\soheil sites image\imageedit__9411602959.gif')
    # data = im.tostring('raw')
    #
    ##app = QApplication([])
    ## image = QImage(data);
    # image = QImage(data, im.size[0], im.size[1], QImage.Format_ARGB32)
    # pix = QPixmap.fromImage(image)
    # lbl = QLabel()
    # lbl.setPixmap(pix)
    # lbl.show(
 def CreateActions(self):
    """ Function to create actions for menus
    """
    self.newAction = QAction( QIcon('new.png'), '&New',
    self, shortcut=QKeySequence.New,
    statusTip="Create a New File",
    triggered=self.newFile)
    self.exitAction = QAction( QIcon(self.icon), 'E&xit',
    self, shortcut="Ctrl+Q",
    statusTip="Exit the Application",
    triggered=self.exitFile)
    self.copyAction = QAction( QIcon('copy.png'), 'C&opy',
    self, shortcut="Ctrl+C",
    statusTip="Copy",
    triggered=self.textEdit.copy)
    self.pasteAction = QAction( QIcon('paste.png'), '&Paste',
    self, shortcut="Ctrl+V",
    statusTip="Paste",
    triggered=self.textEdit.paste)
    self.aboutAction = QAction( QIcon('about.png'), 'A&bout',
    self, statusTip="Displays info about text editor",
    triggered=self.aboutHelp)

    self.openAction = QAction( QIcon('open.png'), 'O&pen',
    self, shortcut=QKeySequence.Open,
    statusTip="Open an existing file",
    triggered=self.openFile)

    self.saveAction = QAction( QIcon('save.png'), '&Save',
    self, shortcut=QKeySequence.Save,
    statusTip="Save the current file to disk",
    triggered=self.saveFile)

    self.cutAction = QAction( QIcon('cut.png'), 'C&ut',
    self, shortcut=QKeySequence.Cut,
    statusTip="Cut the current selection to clipboard",
    triggered=self.textEdit.cut)

    self.undoAction = QAction( QIcon('undo.png'),'Undo', self,
    shortcut=QKeySequence.Undo,
    statusTip="Undo previous action",
    triggered=self.textEdit.undo)

    self.redoAction = QAction( QIcon('redo.png'),'Redo', self,
    shortcut=QKeySequence.Redo,
    statusTip="Redo previous action",
    triggered=self.textEdit.redo)

    self.selectAllAction = QAction( QIcon('selectAll.png'),
    'Select All',
    self, statusTip="Select All",
    triggered=self.textEdit.selectAll)

    self.fontAction = QAction( 'F&ont', self,
    statusTip = "Modify font properties",
    triggered = self.fontChange)

    self.aboutAction = QAction( QIcon('about.png'), 'A&bout',
    self, statusTip="Displays info about text editor",
    # triggered=self.aboutHelp)
    triggered=self.newwindow)

    self.aboutQtAction = QAction("About &Qt", self,
    statusTip="Show the Qt library's About box",
    triggered=qApp.aboutQt)

    self.ss_image = QAction("Insert &.SWF(flash)", self,
    statusTip="Show the Qt library's About box",
    triggered=self.image_ss)

    self.actionAbout = QAction("image &Qt", self,
    statusTip="Show the Qt library's About box",
    triggered=self.openAbout)


# Actual menu bar item creation
 def CreateToolBar(self):
    """ Function to create actual menu bar
    """
    self.mainToolBar = self.addToolBar('Main')
    self.mainToolBar.addAction(self.newAction)
    self.mainToolBar.addSeparator()
    self.mainToolBar.addAction(self.copyAction)
    self.mainToolBar.addAction(self.pasteAction)

# Actual menu bar item creation
 def CreateMenus(self):
    """ Function to create actual menu bar
    """
    self.fileMenu = self.menuBar().addMenu("&File")
    self.fileMenu.addSeparator()
    self.editMenu = self.menuBar().addMenu("&Edit")
    self.helpMenu = self.menuBar().addMenu("&Help")
    self.formatMenu = self.menuBar().addMenu("F&ormat")
 def setAboutButton(self):
    """ Function to set About Button
    """
    self.aboutButton = QPushButton("About", self)
    self.aboutButton.move(110, 100)
    self.aboutButton.clicked.connect(self.showAbout)
 def showAbout(self):
        """ Function to show About Box
        """
        QMessageBox.about(self.aboutButton, "About PySide",
        "PySide is a cross-platform tool for generating GUI Programs.")

 def center(self):
    """ Function to center the application
    """
    qRect = self.frameGeometry()
    centerPoint = QDesktopWidget().availableGeometry().center()
    qRect.moveCenter(centerPoint)
    self.move(qRect.topLeft())
 def quitApp(self):
    """ Function to confirm a message from the user
    """
    userInfo = QMessageBox.question(self, 'Confirmation',
    "This will quit the application. Do you want to Continue?",
    QMessageBox.Yes | QMessageBox.No)
    if userInfo == QMessageBox.Yes:
        myApp.quit()
    if userInfo == QMessageBox.No:
       pass
 def setIconModes(self):
    myIcon1 = QIcon( self.icon)
    myLabel1 = QLabel('sample', self)
    pixmap1 = myIcon1.pixmap(50, 50, QIcon.Active, QIcon.On)
    myLabel1.setPixmap(pixmap1)
    myIcon2 = QIcon( self.icon)
    myLabel2 = QLabel('sample', self)
    pixmap2 = myIcon2.pixmap(50, 50, QIcon.Disabled, QIcon.Off)
    myLabel2.setPixmap(pixmap2)
    myLabel2.move(50, 0)
    myIcon3 = QIcon( self.icon)
    myLabel3 = QLabel('sample', self)
    pixmap3 = myIcon3.pixmap(50, 50, QIcon.Selected, QIcon.On)
    myLabel3.setPixmap(pixmap3)
    myLabel3.move(100, 0)
 def setIcon(self):
    """ Function to set Icon
    """
    from  PySide.QtGui import QPixmap
    pixmap = QPixmap(r'C:\Users\Hamed\Pictures\LED\led.jpg')
    # appIcon = QIcon('C:\Users\Hamed\Documents\soheil sites image\imageedit__9411602959.gif')
    appIcon = QIcon(pixmap)
    self.setWindowIcon(appIcon)

 def setButton(self):
    """ Function to add a quit button
    """
    myButton = QPushButton('Quit', self)
    myButton.move(20, 100)
    # myButton.clicked.connect(myApp.quit)
    myButton.clicked.connect(self.quitApp)
Ejemplo n.º 19
0
class AppWindow(QMainWindow):

    # =====================
    # The Main Window Class
    # =====================

    def __init__(self):
        # ====================
        # Constructor Function
        # ====================

        QMainWindow.__init__(self)
        self.setWindowTitle("Virtua Text Editor")
        self.setGeometry(300, 300, 1024, 768)

        QToolTip.setFont(QFont("Ubuntu", 10, QFont.Normal))
        self.setToolTip('Application Window')

        # ================================
        # Function to setup menus, etc etc
        # ================================
        self.textEdit = QTextEdit()
        self.textEdit.setFont(QFont("Ubuntu", 12, QFont.Normal))
        self.setCentralWidget(self.textEdit)
        self.create_menus()
        self.create_actions()

        self.fileMenu.addAction(self.newAction)
        self.fileMenu.addAction(self.openAction)
        self.fileMenu.addAction(self.saveAction)
        self.fileMenu.addAction(self.saveasAction)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.printAction)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.exitAction)

        self.editMenu.addAction(self.undoAction)
        self.editMenu.addAction(self.redoAction)
        self.editMenu.addAction(self.cutAction)
        self.editMenu.addAction(self.copyAction)
        self.editMenu.addAction(self.pasteAction)
        self.editMenu.addSeparator()
        self.editMenu.addAction(self.selectallAction)
        self.editMenu.addAction(self.deselectallAction)
        self.editMenu.addSeparator()
        self.editMenu.addAction(self.findAction)
        self.editMenu.addAction(self.findReplaceAction)

        self.helpMenu.addAction(self.aboutAction)

        self.app_status_bar = QStatusBar()
        self.app_status_bar.showMessage('Ready, v0.2', 10000)
        self.setStatusBar(self.app_status_bar)

        self.create_toolbar()
        self.toolbar.addAction(self.newAction)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.cutAction)
        self.toolbar.addAction(self.copyAction)
        self.toolbar.addAction(self.pasteAction)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.printAction)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.undoAction)
        self.toolbar.addAction(self.redoAction)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.findAction)
        self.toolbar.addAction(self.findReplaceAction)


    def create_toolbar(self):
        # ===============================
        # Function to create the toolbar.
        # ===============================
        self.toolbar = self.addToolBar('Main')
        self.toolbar.setToolButtonStyle(PySide.QtCore.Qt.ToolButtonTextUnderIcon)

    def newfile(self):
        self.textEdit.setText('')

    # TODO: Create the file/open method
    def openfile(self):
        print "Open File Menu Selected"

    # TODO: Create the file/save method
    def savefile(self):
        print "Save File Menu Selected"

    # TODO: Create the file/saveas method
    def saveasfile(self):
        print "Save As File Menu Selected"

    # TODO: Create the print method
    def print_page(self):
        print "Print Page Selected"

    # TODO: Create the find method
    def find_text(self):
        print "Find text option selected"

    # TODO: Create the replace method
    def find_replace_text(self):
        print "Replace text selected"

    def create_actions(self):
        # =========================================
        # Function to create actions for menu items
        # =========================================

        self.newAction = QAction(QIcon('digital_assets/document-new.svg'), 'New', self)
        self.newAction.setShortcut(QKeySequence.New)
        self.newAction.setStatusTip("Create a New File")
        self.newAction.setIconText("New")
        self.newAction.triggered.connect(self.newfile)

        self.openAction = QAction(QIcon('digital_assets/document-open.svg'), 'Open', self)
        self.openAction.setShortcut(QKeySequence.Open)
        self.openAction.setStatusTip("Open a file")
        self.openAction.triggered.connect(self.openfile)

        self.saveAction = QAction(QIcon('digital_assets/document-save.svg'), 'Save', self)
        self.saveAction.setShortcut(QKeySequence.Save)
        self.saveAction.setStatusTip("Save a file")
        self.saveAction.triggered.connect(self.savefile)

        self.saveasAction = QAction(QIcon('digital_assets/document-save-as.svg'), 'Save As', self)
        self.saveasAction.setShortcut(QKeySequence.SaveAs)
        self.saveasAction.setStatusTip("Save a File As....")
        self.saveasAction.triggered.connect(self.saveasfile)

        self.printAction = QAction(QIcon('digital_assets/document-print.svg'), 'Print', self)
        self.printAction.setShortcut(QKeySequence.Print)
        self.printAction.setStatusTip("Print")
        self.printAction.triggered.connect(self.print_page)

        self.exitAction = QAction(QIcon('digital_assets/application-exit.svg'), 'Exit', self)
        self.exitAction.setShortcut(QKeySequence.Quit)
        self.exitAction.setStatusTip("Exit the Application")
        self.exitAction.triggered.connect(self.quit_application)

        self.undoAction = QAction(QIcon('digital_assets/undo.svg'), 'Undo', self)
        self.undoAction.setShortcut(QKeySequence.Undo)
        self.undoAction.setStatusTip("Undo")
        self.undoAction.triggered.connect(self.textEdit.undo)

        self.redoAction = QAction(QIcon('digital_assets/redo.svg'), 'Redo', self)
        self.redoAction.setShortcut(QKeySequence.Redo)
        self.redoAction.setStatusTip("Redo")
        self.redoAction.triggered.connect(self.textEdit.redo)

        self.cutAction = QAction(QIcon('digital_assets/edit-cut.svg'), 'Cut', self)
        self.cutAction.setShortcut(QKeySequence.Cut)
        self.cutAction.setStatusTip("Cut")
        self.cutAction.setEnabled(False)
        self.cutAction.triggered.connect(self.textEdit.cut)

        self.copyAction = QAction(QIcon('digital_assets/edit-copy.svg'), 'Copy', self)
        self.copyAction.setShortcut(QKeySequence.Copy)
        self.copyAction.setStatusTip("Copy")
        self.copyAction.setEnabled(False)
        self.copyAction.triggered.connect(self.textEdit.copy)

        self.pasteAction = QAction(QIcon('digital_assets/edit-paste.svg'), 'Paste', self)
        self.pasteAction.setShortcut(QKeySequence.Paste)
        self.pasteAction.setStatusTip("Paste")
        self.pasteAction.setEnabled(False)
        self.pasteAction.triggered.connect(self.textEdit.paste)

        self.selectallAction = QAction(QIcon('digital_assets/edit-select-all.svg'), 'Select All', self)
        self.selectallAction.setShortcut(QKeySequence.SelectAll)
        self.selectallAction.setStatusTip("Select All")
        self.selectallAction.triggered.connect(self.textEdit.selectAll)

        self.deselectallAction = QAction(QIcon('digital_assets/edit-select-all.svg'), 'Deselect All', self)
        self.deselectallAction.setShortcut("Shift+Ctrl+A")
        self.deselectallAction.setStatusTip("Deselect All")
        self.deselectallAction.triggered.connect(self.deselect_all_text)

        self.findAction = QAction(QIcon('digital_assets/edit-find.svg'), 'Find', self)
        self.findAction.setShortcut(QKeySequence.Find)
        self.findAction.setStatusTip("Find")
        self.findAction.triggered.connect(self.find_text)

        self.findReplaceAction = QAction(QIcon('digital_assets/edit-find-replace.svg'), 'Replace', self)
        self.findReplaceAction.setShortcut(QKeySequence.Replace)
        self.findReplaceAction.setShortcut("Replace")
        self.findReplaceAction.triggered.connect(self.find_replace_text)

        self.aboutAction = QAction(QIcon('digital_assets/AppIcon.png'), 'About', self)
        self.aboutAction.setStatusTip("Displays info about the application")
        self.aboutAction.triggered.connect(self.show_about)


    def deselect_all_text(self):
        text_cursor = self.textEdit.textCursor()
        text_cursor.clearSelection()
        self.textEdit.setTextCursor(text_cursor)

    def create_menus(self):
        # ================================
        # Function to create the menu bar.
        # ================================
        self.fileMenu = self.menuBar().addMenu("File")
        self.fileMenu.setFont(QFont("Ubuntu", 10, QFont.Normal))
        self.editMenu = self.menuBar().addMenu("Edit")
        self.editMenu.setFont(QFont("Ubuntu", 10, QFont.Normal))
        self.helpMenu = self.menuBar().addMenu("Help")
        self.helpMenu.setFont(QFont("Ubuntu", 10, QFont.Normal))

    def set_icon(self):
        # ===============================
        # Function to set the Window Icon
        # ===============================
        appicon = QIcon('digital_assets/AppIcon.png')
        self.setWindowIcon(appicon)

    def quit_application(self):
        # ================================
        # Function to quit the application
        # ================================
        userinfo = QMessageBox.question(self, "Confirmation", "This will quit, Do you want to continue?",
                                        QMessageBox.Yes | QMessageBox.No)
        if userinfo == QMessageBox.Yes:
            templateApp.quit()
        if userinfo == QMessageBox.No:
            pass

    def show_about(self):
        QMessageBox.about(self, "About Virtua Text Editor",
                          "<b><h3>Virtua Text Editor</h3></b>"
                          "<p><h4>Virtua Text Editor has been written to serve as a template"
                          " that can be used as a basis for creating a working application."
                          " All of the components that make up the core functions of an"
                          " application, the main window, a status bar, menus and dialogs"
                          " are provided here as a basis for writing something new and interesting</h4></p>")

    def center_application(self):
        # ============================================
        # Function to center the Application on screen
        # ============================================
        qrect = self.frameGeometry()
        centerpoint = QDesktopWidget().availableGeometry().center()
        qrect.moveCenter(centerpoint)
        self.move(qrect.topLeft())
Ejemplo n.º 20
0
class MainWindow(QMainWindow):
    """Fenêtre principale du programme"""
    def __init__(self):
        QMainWindow.__init__(self)
        self.setWindowTitle("Main Window")
        self.setGeometry(300, 250, 400, 300)
        self.setWindowIcon(QIcon('Stock/appicon.png'))

    def setupComponent(self):
        """Initialise l'ensemble des éléments de l'application"""
        self.setupStatusBar()
        self.setupZoneText()
        self.setupMenu()
        self.setupToolBar()

    def setupStatusBar(self):
        """Ajoute une barre de status"""
        self.progressBar = QProgressBar()
        self.statusLabel = QLabel('Progression ...')
        self.progressBar.setMaximum(100)
        self.progressBar.setMinimum(0)
        self.statusBar = QStatusBar()
        # # Affiche un message durant 2 sec après ouverture de l'application
        # self.statusBar.showMessage('Please Wait ...', 2000)
        self.progressBar.setValue(10)
        self.statusBar.addWidget(self.statusLabel, 1)
        self.statusBar.addWidget(self.progressBar, 2)
        self.setStatusBar(self.statusBar)

    def setupZoneText(self):
        """Ajout du widget central (zone de texte)"""
        self.textEdit = QTextEdit()
        self.setCentralWidget(self.textEdit)

    def setupMenu(self):
        """Ajout de menus contextuels"""
        self.createActions()
        self.createMenu()
        self.fileMenu.addAction(self.newAction)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.exitAction)
        self.editMenu.addAction(self.copyAction)
        self.editMenu.addSeparator()
        self.editMenu.addAction(self.pasteAction)
        self.helpMenu.addAction(self.aboutAction)

    def setupToolBar(self):
        """Ajout de la barre d'outils"""
        self.mainToolBar = self.addToolBar('Main')
        self.mainToolBar.addAction(self.newAction)
        self.mainToolBar.addSeparator()
        self.mainToolBar.addAction(self.copyAction)
        self.mainToolBar.addAction(self.pasteAction)

    def showProgress(self):
        """Avancement de la barre de progression"""
        while self.progressBar.value() < self.progressBar.maximum():
            self.progressBar.setValue(self.progressBar.value() + 10)
            time.sleep(1/10)
        # self.statusBar.showMessage('Ready', 2000)
        self.statusLabel.setText('Ready !!')

    def createMenu(self):
        """Création de la barre de menu avec 3 menus"""
        self.fileMenu = self.menuBar().addMenu('&Fichier')
        self.editMenu = self.menuBar().addMenu('&Edition')
        self.helpMenu = self.menuBar().addMenu('&About')

    def createActions(self):
        """Création des différentes actions du menu
           '&' permet de surligner une lettre pour acès rapide Alt+lettre
           'shortcut' permet de définir le raccourci de l'action du menu
           'statusTip' permet de modifier l'affichage dans la barre de status
           'triggered' permet de définir l'action à réaliser"""
        self.newAction = QAction('&New', self, shortcut=QKeySequence.New,
                                 statusTip="Créer un nouveau fichier",
                                 triggered=self.newFile)
        self.exitAction = QAction('&Exit', self, shortcut="Ctrl+Q",
                                  statusTip="Quitter l'application",
                                  triggered=self.exitFile)
        self.copyAction = QAction('&Copy', self, shortcut="Ctrl+C",
                                  statusTip="Copier",
                                  triggered=self.textEdit.copy)
        self.pasteAction = QAction('&Paste', self, shortcut="Ctrl+V",
                                   statusTip="Coller",
                                   triggered=self.textEdit.paste)
        self.aboutAction = QAction('&About', self,
                                   statusTip="Infos à propos de l'éditeur",
                                   triggered=self.aboutHelp)

    def newFile(self):
        """Efface le contenu du widget de text"""
        self.textEdit.setText('')

    def exitFile(self):
        """Ferme le programme"""
        self.close()

    def aboutHelp(self):
        """Affiche des renseignements sur le logiciel"""
        QMessageBox.about(self, "About this application",
                          "Just a simple text editor using Menu Bar")
Ejemplo n.º 21
0
  def setupUi(self, MainWindow):
      MainWindow.setObjectName("MainWindow")
      MainWindow.setFixedSize(800, 600)
      self.centralwidget = QWidget(MainWindow)
      self.centralwidget.setObjectName("centralwidget")
      self.FilterLbl = QLabel(self.centralwidget)
      self.FilterLbl.setGeometry(QtCore.QRect(30, 150, 60, 15))
      self.FilterLbl.setObjectName("FilterLbl")
      self.FilterCB = QComboBox(self.centralwidget)
      self.FilterCB.setGeometry(QtCore.QRect(450, 150, 100, 22))
      self.FilterCB.setObjectName("FilterCB")
      self.FilterCB.addItem("")
      self.FilterCB.addItem("")
      self.FilterCB.addItem("")
      self.FilterCB.addItem("")         
      self.FilterTF = QLineEdit(self.centralwidget)
      self.FilterTF.setGeometry(QtCore.QRect(100, 150, 320, 20))        
      self.tableView = QTableWidget(self.centralwidget)
      self.tableView.setGeometry(QtCore.QRect(10, 180, 781, 511))
      self.tableView.setObjectName("tableView")
      self.tableView.setColumnCount(4)
      self.tableView.setRowCount(0)
      item = QTableWidgetItem("Cena za kg/l")
      self.tableView.setHorizontalHeaderItem(0, item)
      item = QTableWidgetItem("Cena ze kus")
      self.tableView.setHorizontalHeaderItem(1, item)
      item = QTableWidgetItem(u"Gramaž")
      self.tableView.setHorizontalHeaderItem(2, item)
      item = QTableWidgetItem("Popis")
      item.setTextAlignment(QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter|QtCore.Qt.AlignCenter)
      font = QtGui.QFont()
      font.setPointSize(8)
      item.setFont(font)
      self.tableView.setHorizontalHeaderItem(3, item)
      self.tableView.horizontalHeader().setStretchLastSection(True)
      
      self.SaveBtn = QPushButton(self.centralwidget)
      self.SaveBtn.setGeometry(QtCore.QRect(30, 10, 100, 23))
      self.SaveBtn.setObjectName("SaveBtn")
      self.PrintSelectedToFileBtn = QPushButton(self.centralwidget)
      self.PrintSelectedToFileBtn.setGeometry(QtCore.QRect(225, 10, 100, 23))        
      self.PrintSelectedToFileBtn.setObjectName("PrintSelectedToFileBtn")
      self.PriceForUnitTF = QLineEdit(self.centralwidget)
      self.PriceForUnitTF.setGeometry(QtCore.QRect(100, 70, 113, 20))
      self.PriceForUnitTF.setObjectName("PriceForUnitTF")
      self.PriceForUnitLbl = QLabel(self.centralwidget)
      self.PriceForUnitLbl.setGeometry(QtCore.QRect(30, 70, 60, 13))
      self.PriceForUnitLbl.setObjectName("PriceForUnitLbl")
      self.ArtikelTF = QLineEdit(self.centralwidget)
      self.ArtikelTF.setGeometry(QtCore.QRect(100, 100, 113, 20))
      self.ArtikelTF.setObjectName("ArtikelTF")
      self.ArtikelLbl = QLabel(self.centralwidget)
      self.ArtikelLbl.setGeometry(QtCore.QRect(30, 100, 46, 13))
      self.ArtikelLbl.setObjectName("ArtikelLbl")
      self.DescriptionLbl = QLabel(self.centralwidget)
      self.DescriptionLbl.setGeometry(QtCore.QRect(455, 70, 75, 13))
      self.DescriptionLbl.setObjectName("DescriptionLbl")
      self.UnitLbl = QLabel(self.centralwidget)
      self.UnitLbl.setGeometry(QtCore.QRect(250, 70, 60, 15))
      self.UnitLbl.setObjectName("UnitLbl")
      self.WeightLbl = QLabel(self.centralwidget)
      self.WeightLbl.setGeometry(QtCore.QRect(250, 100, 60, 13))
      self.WeightLbl.setObjectName("UnitLbl")
      self.WeightTF = QLineEdit(self.centralwidget)
      self.WeightTF.setGeometry(QtCore.QRect(320, 100, 100, 20))
      self.WeightTF.setObjectName("WeightTF")        
      self.UnitCB = QComboBox(self.centralwidget)
      self.UnitCB.setGeometry(QtCore.QRect(320, 70, 100, 22))
      self.UnitCB.setObjectName("UnitCB")
      self.UnitCB.addItem("")
      self.UnitCB.addItem("")
      self.DescriptionTE = QPlainTextEdit(self.centralwidget)
      self.DescriptionTE.setGeometry(QtCore.QRect(540, 30, 241, 61))
      self.DescriptionTE.setObjectName("DescriptionTE")
      self.PrintToFileBtn = QPushButton(self.centralwidget)
      self.PrintToFileBtn.setGeometry(QtCore.QRect(140, 10, 75, 23))
      self.PrintToFileBtn.setObjectName("PrintToFileBtn")
      self.AddRecordBtn = QPushButton(self.centralwidget)
      self.AddRecordBtn.setGeometry(QtCore.QRect(450, 100, 75, 23))
      self.AddRecordBtn.setObjectName("AddRecordBtn")        
      self.SaveChangeBtn = QPushButton(self.centralwidget)
      self.SaveChangeBtn.setGeometry(QtCore.QRect(550, 100, 75, 23))
      self.SaveChangeBtn.setObjectName("SaveChangeBtn")
      self.DeleteRecordBtn = QPushButton(self.centralwidget)
      self.DeleteRecordBtn.setGeometry(QtCore.QRect(650, 100, 75, 23))
      self.DeleteRecordBtn.setObjectName("DeleteRecordBtn")
      MainWindow.setCentralWidget(self.centralwidget)
      self.menubar = QMenuBar(MainWindow)
      self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
      self.menubar.setObjectName("menubar")
      MainWindow.setMenuBar(self.menubar)
      self.statusbar = QStatusBar(MainWindow)
      self.statusbar.setObjectName("statusbar")
 
      self.FilterTF.textChanged.connect(self.on_lineEdit_textChanged)
      self.FilterCB.currentIndexChanged.connect(self.on_comboBox_currentIndexChanged)
      self.retranslateUi(MainWindow)
      QtCore.QMetaObject.connectSlotsByName(MainWindow)
Ejemplo n.º 22
0
class Ui_MainWindow(object):
    
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.setFixedSize(800, 600)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.FilterLbl = QLabel(self.centralwidget)
        self.FilterLbl.setGeometry(QtCore.QRect(30, 150, 60, 15))
        self.FilterLbl.setObjectName("FilterLbl")
        self.FilterCB = QComboBox(self.centralwidget)
        self.FilterCB.setGeometry(QtCore.QRect(450, 150, 100, 22))
        self.FilterCB.setObjectName("FilterCB")
        self.FilterCB.addItem("")
        self.FilterCB.addItem("")
        self.FilterCB.addItem("")
        self.FilterCB.addItem("")         
        self.FilterTF = QLineEdit(self.centralwidget)
        self.FilterTF.setGeometry(QtCore.QRect(100, 150, 320, 20))        
        self.tableView = QTableWidget(self.centralwidget)
        self.tableView.setGeometry(QtCore.QRect(10, 180, 781, 511))
        self.tableView.setObjectName("tableView")
        self.tableView.setColumnCount(4)
        self.tableView.setRowCount(0)
        item = QTableWidgetItem("Cena za kg/l")
        self.tableView.setHorizontalHeaderItem(0, item)
        item = QTableWidgetItem("Cena ze kus")
        self.tableView.setHorizontalHeaderItem(1, item)
        item = QTableWidgetItem(u"Gramaž")
        self.tableView.setHorizontalHeaderItem(2, item)
        item = QTableWidgetItem("Popis")
        item.setTextAlignment(QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter|QtCore.Qt.AlignCenter)
        font = QtGui.QFont()
        font.setPointSize(8)
        item.setFont(font)
        self.tableView.setHorizontalHeaderItem(3, item)
        self.tableView.horizontalHeader().setStretchLastSection(True)
        
        self.SaveBtn = QPushButton(self.centralwidget)
        self.SaveBtn.setGeometry(QtCore.QRect(30, 10, 100, 23))
        self.SaveBtn.setObjectName("SaveBtn")
        self.PrintSelectedToFileBtn = QPushButton(self.centralwidget)
        self.PrintSelectedToFileBtn.setGeometry(QtCore.QRect(225, 10, 100, 23))        
        self.PrintSelectedToFileBtn.setObjectName("PrintSelectedToFileBtn")
        self.PriceForUnitTF = QLineEdit(self.centralwidget)
        self.PriceForUnitTF.setGeometry(QtCore.QRect(100, 70, 113, 20))
        self.PriceForUnitTF.setObjectName("PriceForUnitTF")
        self.PriceForUnitLbl = QLabel(self.centralwidget)
        self.PriceForUnitLbl.setGeometry(QtCore.QRect(30, 70, 60, 13))
        self.PriceForUnitLbl.setObjectName("PriceForUnitLbl")
        self.ArtikelTF = QLineEdit(self.centralwidget)
        self.ArtikelTF.setGeometry(QtCore.QRect(100, 100, 113, 20))
        self.ArtikelTF.setObjectName("ArtikelTF")
        self.ArtikelLbl = QLabel(self.centralwidget)
        self.ArtikelLbl.setGeometry(QtCore.QRect(30, 100, 46, 13))
        self.ArtikelLbl.setObjectName("ArtikelLbl")
        self.DescriptionLbl = QLabel(self.centralwidget)
        self.DescriptionLbl.setGeometry(QtCore.QRect(455, 70, 75, 13))
        self.DescriptionLbl.setObjectName("DescriptionLbl")
        self.UnitLbl = QLabel(self.centralwidget)
        self.UnitLbl.setGeometry(QtCore.QRect(250, 70, 60, 15))
        self.UnitLbl.setObjectName("UnitLbl")
        self.WeightLbl = QLabel(self.centralwidget)
        self.WeightLbl.setGeometry(QtCore.QRect(250, 100, 60, 13))
        self.WeightLbl.setObjectName("UnitLbl")
        self.WeightTF = QLineEdit(self.centralwidget)
        self.WeightTF.setGeometry(QtCore.QRect(320, 100, 100, 20))
        self.WeightTF.setObjectName("WeightTF")        
        self.UnitCB = QComboBox(self.centralwidget)
        self.UnitCB.setGeometry(QtCore.QRect(320, 70, 100, 22))
        self.UnitCB.setObjectName("UnitCB")
        self.UnitCB.addItem("")
        self.UnitCB.addItem("")
        self.DescriptionTE = QPlainTextEdit(self.centralwidget)
        self.DescriptionTE.setGeometry(QtCore.QRect(540, 30, 241, 61))
        self.DescriptionTE.setObjectName("DescriptionTE")
        self.PrintToFileBtn = QPushButton(self.centralwidget)
        self.PrintToFileBtn.setGeometry(QtCore.QRect(140, 10, 75, 23))
        self.PrintToFileBtn.setObjectName("PrintToFileBtn")
        self.AddRecordBtn = QPushButton(self.centralwidget)
        self.AddRecordBtn.setGeometry(QtCore.QRect(450, 100, 75, 23))
        self.AddRecordBtn.setObjectName("AddRecordBtn")        
        self.SaveChangeBtn = QPushButton(self.centralwidget)
        self.SaveChangeBtn.setGeometry(QtCore.QRect(550, 100, 75, 23))
        self.SaveChangeBtn.setObjectName("SaveChangeBtn")
        self.DeleteRecordBtn = QPushButton(self.centralwidget)
        self.DeleteRecordBtn.setGeometry(QtCore.QRect(650, 100, 75, 23))
        self.DeleteRecordBtn.setObjectName("DeleteRecordBtn")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
   
        self.FilterTF.textChanged.connect(self.on_lineEdit_textChanged)
        self.FilterCB.currentIndexChanged.connect(self.on_comboBox_currentIndexChanged)
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def myFilter(self,col=None):
        filt = self.FilterTF.text()
        for ix in range(self.tableView.rowCount()):
            match = False
            if col == None:
                for jx in range(self.tableView.columnCount()):
                    item = self.tableView.item(ix,jx)
                    if filt in item.text():
                        match = True
                        break
                self.tableView.setRowHidden(ix, not match)
            else:
                item = self.tableView.item(ix, col)
                if filt in item.text():
                    match = True
                self.tableView.setRowHidden(ix, not match)

    #@QtCore.pyqtSlot(str)
    def on_lineEdit_textChanged(self, text):
        self.myFilter()

    #@QtCore.pyqtSlot(int)
    def on_comboBox_currentIndexChanged(self, index):
        self.myFilter(col=index)
        
    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Stitky - {0}".format(__version__)))
        self.SaveBtn.setText(_translate("MainWindow", "Uloz stav tabulky"))
        self.PrintSelectedToFileBtn.setText(_translate("MainWindow", "Tisk vybranych"))
        self.PriceForUnitLbl.setText(_translate("MainWindow", "Cena za kus:"))
        self.ArtikelLbl.setText(_translate("MainWindow", "Artikl:"))
        self.DescriptionLbl.setText(_translate("MainWindow", "Popis produktu:"))
        self.UnitLbl.setText(_translate("MainWindow", "Jednotka:"))
        self.FilterLbl.setText(_translate("MainWindow", "Filtr:"))
        self.WeightLbl.setText(_translate("MainWindow", "Hmotnost:"))
        self.PrintToFileBtn.setText(_translate("MainWindow", "Vytvor txt"))
        self.SaveChangeBtn.setText(_translate("MainWindow", "Uloz zmeny"))
        self.AddRecordBtn.setText(_translate("MainWindow", "Pridej zaznam"))
        self.DeleteRecordBtn.setText(_translate("MainWindow", "Smaz zaznam"))
        self.UnitCB.setItemText(0, _translate("MainWindow", "g"))
        self.UnitCB.setItemText(1, _translate("MainWindow", "ml"))
        self.FilterCB.setItemText(0, _translate("MainWindow", "Cena za kg/l"))
        self.FilterCB.setItemText(1, _translate("MainWindow", "Cena ze kus"))
        self.FilterCB.setItemText(2, _translate("MainWindow", "Gramaz"))
        self.FilterCB.setItemText(3, _translate("MainWindow", "Popis"))
Ejemplo n.º 23
0
class SafeLock(QWidget):
    def __init__(self):
        super(SafeLock, self).__init__()
        main_layout = QVBoxLayout(self)
        self.Version = '0.5 beta'
        self.s_error = "QStatusBar{color:red;font-weight:1000;}"
        self.s_loop = "QStatusBar{color:black;font-weight:1000;}"
        self.s_norm = "QStatusBar{color:blue;font-style:italic;"
        self.s_norm += "font-weight:500;}"
        self.Processing = None
        self.CP = None
        self.PPbar = None
        self.key = None
        self.DFiles = []

        self.picon = r_path("images/favicon.png")
        self.plogo = r_path("images/logo.png")
        if name == 'nt':
            self.picon = r_path("images\\favicon.png")
            self.plogo = r_path("images\\logo.png")
        self.icon = QIcon(self.picon)
        self.logo = QIcon(self.plogo)
        self.center()
        self.setStyle()
        self.setMW(main_layout)
        self.setSB(main_layout)
        self.show()

    def db(self, password="******", dbname="untitled.sld", dc=True):
        eng = create_engine("sqlite:///%s" % dbname,
                            connect_args={'check_same_thread': False})
        Base = declarative_base(bind=eng)
        Session = sessionmaker(bind=eng)
        session = Session()

        class Identifier(Base):
            __tablename__ = "identifier"
            id = Column(Integer, primary_key=True)
            version = Column(Binary)
            kvd = Column(Binary)

            def __init__(self, version, kvd):
                self.id = 0
                self.version = version
                self.kvd = kvd

        class Folder(Base):
            __tablename__ = 'folders'
            id = Column(Integer, primary_key=True)
            path = Column(String)

            def __init__(self, path="Empty"):
                self.path = path

        class File(Base):
            __tablename__ = 'files'
            id = Column(Integer, primary_key=True)
            name = Column(String)
            f_id = Column(Integer, ForeignKey('folders.id'), nullable=True)
            bb = Column(Binary)

            def __init__(self, name="empty", f_id=0, bb=1010):
                self.name = name
                self.f_id = f_id
                self.bb = bb

        if dc:
            Base.metadata.create_all()
            enc = encryptit(
                sha256(self.Version).digest(),
                sha256(password).digest())
            session.add(Identifier(enc[0], enc[1]))
            session.commit()

        return [eng, Base, session, File, Folder, Identifier, password]

    def checkP(self, db):
        try:
            d = db[2].query(db[5]).filter_by(id=0).first()
            if d is not None:
                if isenct(self.Version, d.version, db[6], d.kvd):
                    return True
        except:
            pass
        return False

    def setStyle(self):
        self.setMaximumWidth(410)
        self.setMinimumWidth(410)
        self.setMaximumHeight(370)
        self.setMinimumHeight(370)
        self.setWindowIcon(self.icon)
        self.activateWindow()
        self.setWindowTitle("safelock " + self.Version)
        self.setToolTip("Just drag and drop any files or folders" +
                        " to ecrypt or a .sld file to decrypt")
        self.setAcceptDrops(True)
        self.show()

    def center(self):
        qrect = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qrect.moveCenter(cp)
        self.move(qrect.topLeft())

    def setMW(self, ml):
        ll = QVBoxLayout()
        self.mIcon = QLabel()
        self.mIcon.setAlignment(Qt.AlignCenter)
        mmicon = self.logo.pixmap(250, 230, QIcon.Active, QIcon.On)
        self.mIcon.setPixmap(mmicon)
        self.mInst = QLabel(
            "<center>(Drag and drop files or folders to encrypt them)<br>" +
            "(Drap and drop .sld file to decrypt it)<br>" +
            "<u>2GB max single file size to encrypt</u></center>")
        font = QFont()
        font.setPointSize(13)
        font.setBold(True)
        font.setWeight(75)
        self.fInst = QLabel('<center>| Double-Click for about |</center>')
        self.mInst.setFont(font)
        ll.addWidget(self.mIcon)
        ll.addWidget(self.mInst)
        ll.addWidget(self.fInst)
        ml.addLayout(ll)

    def setSB(self, ml):
        self.statusb = QStatusBar()
        ml.addWidget(self.statusb)

    def modSB(self):
        if self.PPbar is None:
            self.PPbar = True
            self.statusb.clear()
            self.pbar = QProgressBar()
            self.pbar.setMaximum(100)
            self.pbar.setMinimum(0)
            self.plabel = QLabel()
            self.statusb.addWidget(self.plabel, 0.5)
            self.statusb.addWidget(self.pbar, 3)
        else:
            self.PPbar = None
            self.statusb.removeWidget(self.plabel)
            self.statusb.removeWidget(self.pbar)
            self.statusb.clear()

    def saveFile(self, fl):
        fname, _ = QFileDialog.getSaveFileName(self, "Save encrypted file", fl,
                                               "Safelock file (*.sld)")
        if '.' in fname:
            tm = fname.split('.')
            tm = tm[len(tm) - 1]
            if tm == "sld":
                try:
                    if path.isfile(fname):
                        remove(fname)
                except:
                    pass
                return fname
        if len(fname) <= 0:
            return None
        fname += ".sld"
        try:
            if path.isfile(fname):
                remove(fname)
        except:
            pass
        return fname

    def extTo(self, fl):
        fname = QFileDialog.getExistingDirectory(self, "Extract files to", fl)
        if len(fname) <= 0:
            return None
        return fname

    def getPass(self):
        passwd, re = QInputDialog.getText(self, "Password", "Enter password :"******"Something went wrong !"):
        QMessageBox.critical(self, "Error", msg)
        return True

    def aboutMsgg(self):
        Amsg = "<center>All credit reserved to the author of "
        Amsg += "safelock %s " % self.Version
        Amsg += ", This work is a free, open-source project licensed "
        Amsg += " under Mozilla Public License version 2.0 . <br><br>"
        Amsg += " visit for more info or report:<br> "
        Amsg += "<b><a href='https://safe-lock.github.io'> "
        Amsg += "https://safe-lock.github.io/ </a> </b></center>"
        QMessageBox.about(self, "About", Amsg)
        return True

    def getSession(self):
        self.eng = eng(self.password, self.dbname)
        Session = sessionmaker(bind=self.eng)
        self.Base = declarative_base(bind=self.eng)
        self.Base.metadata.create_all()
        self.session = Session()
        return self.session

    def dragEnterEvent(self, e):
        if e.mimeData().hasUrls:
            e.accept()
        else:
            e.ignore()

    def dragMoveEvent(self, e):
        if e.mimeData().hasUrls:
            e.accept()
        else:
            e.ignore()

    def dropEvent(self, e):
        if e.mimeData().hasUrls:
            e.setDropAction(Qt.CopyAction)
            e.accept()
            self.DFiles = []
            for url in e.mimeData().urls():
                try:
                    if sysname == 'darwin':
                        from Foundation import NSURL
                        fname = NSURL.URLWithString_(
                            url.toString()).filePathURL().path()
                    else:
                        fname = url.toLocalFile()
                    self.DFiles.append(fname)
                except:
                    pass
            self.dealD(self.DFiles)
        else:
            event.ignore()

    def in_loop(self):
        if self.Processing is None:
            self.Processing = True
            self.setAcceptDrops(False)
            self.mIcon.setEnabled(False)
            self.mInst.setEnabled(False)
            self.fInst.setText("<center>| Double-Click to cancel |</center>")
            self.setToolTip("Double-Click anywhere to cancel")
        else:
            self.Processing = None
            self.setAcceptDrops(True)
            self.mIcon.setEnabled(True)
            self.mInst.setEnabled(True)
            self.fInst.setText("<center>| Double-Click for about |</center>")
            self.setToolTip("Just drag and drop any files or folders" +
                            " to ecrypt or a .sld file to decrypt")

    def dealD(self, files):
        def tpp(inp):
            a = path.basename(inp)
            return inp.replace(a, '')

        if len(files) < 1:
            return False
        elif len(files) >= 1:
            if len(files) == 1:
                tf = files[0].split('.')
                tf = tf[len(tf) - 1]
                if tf == 'sld':
                    pw = self.getPass()
                    if pw is None:
                        self.errorMsg("You can't set an empty password !")
                        return False
                    elif not pw:
                        return False
                    if not self.checkP(
                            self.db(sha256(pw).digest(), files[0], dc=False)):
                        self.errorMsg("Wrong password entered, try again.")
                        return False
                    else:
                        fold = self.extTo(tpp(files[0]))
                        if fold is not None:
                            self.CP = fold
                            self.in_loop()
                            self.P = DecryptTH(fold,
                                               self.db(pw, files[0], dc=False),
                                               sha256(pw).digest())
                            self.P.start()
                            self.P.somesignal.connect(self.handleStatusMessage)
                            self.P.setTerminationEnabled(True)
                            return True
            pw = self.getPass()
            if pw is None:
                self.errorMsg("You can't set an empty password !")
            elif not pw:
                pass
            else:
                fil = self.saveFile(tpp(files[0]))
                if fil is not None:
                    if path.isfile(fil):
                        try:
                            remove(fil)
                        except:
                            pass
                    self.CP = fil
                    self.in_loop()
                    self.P = EncryptTH(files, self.db(pw, fil),
                                       sha256(pw).digest())
                    self.P.start()
                    self.P.somesignal.connect(self.handleStatusMessage)
                    self.P.setTerminationEnabled(True)
        return True

    @Slot(object)
    def handleStatusMessage(self, message):
        self.statusb.setStyleSheet(self.s_loop)

        def getIT(f, o):
            return int((f / o) * 100)

        mm = message.split('/')
        if mm[len(mm) - 1] == '%':
            if self.PPbar is None:
                self.modSB()
            self.pbar.setValue(getIT(int(mm[0]), int(mm[1])))
            self.setWindowTitle("Processing : " +
                                str(getIT(int(mm[0]), int(mm[1]))) + "%")
            self.plabel.setText(mm[0] + '/' + mm[1])
        else:
            self.unsetCursor()
            if self.PPbar is not None:
                self.modSB()
            if message[:7] == '# Error':
                if self.Processing:
                    self.in_loop()
                self.statusb.setStyleSheet(self.s_error)
                self.cleanup()
            elif message[:6] == '# Stop':
                self.statusb.setStyleSheet(self.s_error)
            elif message[:6] == '# Done':
                if self.Processing:
                    self.in_loop()
                self.statusb.setStyleSheet(self.s_norm)
            elif message == "# Loading":
                self.setCursor(Qt.BusyCursor)
                self.statusb.setStyleSheet(self.s_norm)
            self.setWindowTitle('safelock ' + self.Version)
            self.statusb.showMessage(message)

    def mousePressEvent(self, event):
        if event.type() == QEvent.Type.MouseButtonDblClick:
            if self.Processing is None:
                self.aboutMsgg()
            else:
                self.closeEvent()

    def closeEvent(self, event=None):
        if self.Processing is not None:
            if event is not None:
                r = QMessageBox.question(
                    self, "Making sure",
                    "Are you sure you want to exit, during an active" +
                    " process ?", QMessageBox.Yes | QMessageBox.No)
            else:
                r = QMessageBox.question(self, "Making sure",
                                         "Are you sure, you to cancel ?",
                                         QMessageBox.Yes | QMessageBox.No)
            if r == QMessageBox.Yes:
                self.P.stop()
                self.cleanup()
                if event is not None:
                    self.in_loop()
                    event.accept()
                else:
                    self.in_loop()
            else:
                if event is not None:
                    event.ignore()
        else:
            if self.CP is not None:
                try:
                    if path.isfile(self.CP + '-journal'):
                        remove(self.CP + '-journal')
                except:
                    pass
            if event is not None:
                event.accept()

    def cleanup(self):
        if self.CP is not None:
            try:
                if path.isfile(self.CP + '-journal'):
                    remove(self.CP + '-journal')
                if path.isfile(self.CP):
                    remove(self.CP)
            except:
                pass
Ejemplo n.º 24
0
 def setSB(self, ml):
     self.statusb = QStatusBar()
     ml.addWidget(self.statusb)
Ejemplo n.º 25
0
    def __init__(self):
        QWidget.__init__(self)
        self.setWindowTitle("EEG Pilot Dashboard")
        self.setGeometry(0, 0, 750, 800)
        # self.setGeometry(300, 300, 750, 800)
        self.dashboard = EegCarDashboard()
        self.dashboard.set_max_throttle(DEFAULT_MAX_THROTTLE)
        self.dashboard.set_backward_max_throttle(DEFAULT_MAX_BACK_THROTTLE)

        self.layout = QVBoxLayout(self)

        # Drive Setting
        self.rc_mode = QCheckBox('Remote Control', self)
        self.rc_mode.stateChanged.connect(self.remote_control)

        self.rc_stright_mode = QCheckBox('RC Stright', self)
        self.rc_stright_mode.stateChanged.connect(self.stright_control)

        self.keep_mode_checkbox = QCheckBox('Keep Mode', self)
        self.keep_mode_checkbox.stateChanged.connect(self.keep_mode_control)

        self.power_handle_mode_checkbox = QCheckBox('Power Handle', self)
        self.power_handle_mode_checkbox.stateChanged.connect(self.power_handle_mode_control)

        self.ignore_eeg_input = QCheckBox('Ignore Eeg Input', self)
        self.ignore_eeg_input.stateChanged.connect(self.ignore_eeg_input_control)

        drive_layout = QHBoxLayout(self)
        drive_layout.addWidget(self.rc_mode)
        drive_layout.addWidget(self.rc_stright_mode)
        drive_layout.addWidget(self.keep_mode_checkbox)
        drive_layout.addWidget(self.power_handle_mode_checkbox)
        drive_layout.addWidget(self.ignore_eeg_input)

        drive_groupbox = QtGui.QGroupBox("Drive Status & Setting")
        drive_groupbox.setLayout(drive_layout)

        # Throttle Setting
        self.throttle_slider = QSlider(Qt.Horizontal)
        self.throttle_slider.setFocusPolicy(Qt.StrongFocus)
        self.throttle_slider.setTickPosition(QSlider.TicksBothSides)
        self.throttle_slider.setTickInterval(10)
        self.throttle_slider.setSingleStep(10)
        self.throttle_slider.setValue(DEFAULT_MAX_THROTTLE)

        self.throttle_slider.valueChanged.connect(self.throttle_slider.setValue)
        self.connect(self.throttle_slider, SIGNAL("valueChanged(int)"), self.setSliderMaxThrottle)
        self.throttle_label = QLabel('Max Throttle (%): ', self)


        self.maxThrottle = QLineEdit(str(DEFAULT_MAX_THROTTLE))
        # self.maxThrottle.textChanged[str].connect(self.setMaxThrottle)
        self.maxThrottle.editingFinished.connect(self.setMaxThrottle)
        self.maxThrottle.setMaxLength(2)
        self.maxThrottle.setMaximumWidth(40)

        self.backwardMaxThrottle = QLineEdit(str(DEFAULT_MAX_BACK_THROTTLE))
        # self.maxThrottle.textChanged[str].connect(self.setMaxThrottle)
        self.backwardMaxThrottle.editingFinished.connect(self.setBackwardMaxThrottle)
        self.backwardMaxThrottle.setMaxLength(2)
        self.backwardMaxThrottle.setMaximumWidth(40)

        throttle_layout = QHBoxLayout(self)
        throttle_layout.addWidget(self.throttle_label)
        throttle_layout.addWidget(self.throttle_slider)
        throttle_layout.addWidget(QLabel("Forward Max:"))
        throttle_layout.addWidget(self.maxThrottle)

        throttle_layout.addWidget(QLabel("Backward Max:"))
        throttle_layout.addWidget(self.backwardMaxThrottle)

        throttle_groupbox = QtGui.QGroupBox("Max Throttle Setting (30-99)")
        throttle_groupbox.setLayout(throttle_layout)

        # Steering
        self.steering_label = QLabel('Turn Range', self)
        self.steering_turn_range_slider = QSlider(Qt.Horizontal)
        self.steering_turn_range_slider.setFocusPolicy(Qt.StrongFocus)
        self.steering_turn_range_slider.setTickPosition(QSlider.TicksBothSides)
        self.steering_turn_range_slider.setRange(1, 9)
        # self.steering_slider.setMinimum(2)
        # self.steering_slider.setMaximum(8)
        self.steering_turn_range_slider.setMinimum(4)
        self.steering_turn_range_slider.setMaximum(8)
        self.steering_turn_range_slider.setTickInterval(1)
        self.steering_turn_range_slider.setSingleStep(1)
        self.steering_turn_range_slider.setValue(6)
        self.steering_turn_range_slider.valueChanged.connect(self.steering_turn_range_slider.setValue)
        self.connect(self.steering_turn_range_slider, SIGNAL("valueChanged(int)"), self.setSteeringTurnRangeValue)

        self.steering_adjust_label = QLabel(' Home Adjust ', self)
        self.steering_move_left_button = QPushButton('<Left+', self)
        self.steering_current_pos = QLabel('0', self)
        self.steering_move_right_button = QPushButton('-Right>', self)

        self.steering_move_ticks = QLineEdit(str(5000))
        self.steering_move_ticks.editingFinished.connect(self.set_steering_move_ticks_value)
        self.steering_move_ticks.setMaxLength(5)
        self.steering_move_ticks.setMaximumWidth(50)

        self.steering_reset = QPushButton('Reset', self)

        self.steering_move_left_button.clicked.connect(self.steering_move_left)
        self.steering_move_right_button.clicked.connect(self.steering_move_right)
        self.steering_reset.clicked.connect(self.steering_reset_position)

        steering_layout = QHBoxLayout(self)
        steering_layout.addWidget(self.steering_label)
        # steering_layout.addWidget(self.steering_slider)
        steering_layout.addWidget(self.steering_turn_range_slider)
        steering_layout.addWidget(self.steering_adjust_label)
        steering_layout.addWidget(self.steering_move_left_button)


        steering_layout.addWidget(self.steering_current_pos)
        steering_layout.addWidget(self.steering_move_right_button)
        steering_layout.addWidget(self.steering_move_ticks)
        steering_layout.addWidget(self.steering_reset)

        steering_groupbox = QtGui.QGroupBox("Steering Setting")
        steering_groupbox.setLayout(steering_layout)

        self.layout.addWidget(self.dashboard, 2)
        self.layout.addWidget(drive_groupbox)
        self.layout.addWidget(throttle_groupbox)
        self.layout.addWidget(steering_groupbox)

        self.statusBar = QStatusBar()
        self.statusBar.showMessage('Ready', 2000)
        self.layout.addWidget(self.statusBar)

        self.setIcon()
        self.show()

        # save the state
        self.default_backgroundcolor = self.palette().color(QtGui.QPalette.Background)
        self.previos_steering = 50
        self.init_keep_mode()
        self.init_power_handle_mode()
Ejemplo n.º 26
0
class EegCarDashboardWindow(QWidget):

    def setSliderMaxThrottle(self, x):
        self.setMaxThrottle(x)
        # self.dashboard.set_throttle(x)
        # self.dashboard.wheel.forward(x)

    def setSteeringValue(self, x):
        # x range is 1-9 need to scale (10-90)
        x = x*10
        self.dashboard.set_steering(x)
        # self.dashboard.steering.turn_by_position(x)
        pot = 1.5
        self.dashboard.steering.turn_by_position(x, pot)

    def setSteeringTurnRangeValue(self, x):
        ticks = int(100000 * (x/10.0)) # max is 100000
        # print "STEERING TURN TICKS %d" % ticks
        self.dashboard.set_steering_eeg_turn_ticks(ticks)

    def steering_update_current_pos(self):
        # x = int(self.steering_current_pos.text()) + delta_x
        # while check busy
        ## read position
        ## print 'current pos %d' % x

        ticks = int(self.steering_move_ticks.text())
        seconds = int(ticks/(DEFAULT_STEERING_SPEED*7))
        seconds = seconds + 1 # at least one second
        ending_time = time.time() + seconds
        while time.time() < ending_time:
            # print "ENDNIG: %d" % ending_time
            # print "CURRENT: %d" % time.time()
            self.steering_set_current_pos(self.dashboard.steering.get_current_location())

    def steering_set_current_pos(self, x):
        self.steering_current_pos.setText(str(x))    

    def steering_move_left(self):
        ticks = int(self.steering_move_ticks.text())
        # Stepping Motor MOVE!
        self.dashboard.steering.stepping_driver.forward(ticks)
        self.setMessage('Steering left')
        self.steering_update_current_pos()

    def steering_move_right(self):
        ticks = int(self.steering_move_ticks.text())
        # Stepping Motor MOVE!
        self.dashboard.steering.stepping_driver.backward(ticks)
        self.setMessage('Steering right')
        self.steering_update_current_pos()

    def set_steering_move_ticks_value(self):
        self.steering_move_ticks.blockSignals(True) # update line edit
        ticks = int(self.steering_move_ticks.text())
        self.steering_move_ticks.setText(str(ticks)) 
        self.steering_move_ticks.blockSignals(False)
        self.steering_move_ticks.setModified(True)

        if self.steering_move_ticks.isModified():
            self.steering_move_ticks.clearFocus()
        self.maxThrottle.setModified(False)

    def steering_reset_position(self):
        # RESET
        self.setMessage('Steering Controller Reset')
        self.dashboard.steering.stepping_driver.reset() # reset
        self.dashboard.steering.stepping_driver.set_speed(DEFAULT_STEERING_SPEED) # set speed
        self.steering_update_current_pos()

    def setMessage(self, msg):
        self.statusBar.showMessage(msg, 2000)

    def remote_control(self, state):
        if state == QtCore.Qt.Checked:
            self.dashboard.set_rc_mode(True)
            self.setMessage('SET RC MODE')
        else:
            self.dashboard.set_rc_mode(False)
            self.setMessage('CLEAR RC MODE')

    def keep_mode_control(self, state):
        if state == QtCore.Qt.Checked:
            self.keep_mode = True
            self.setMessage('Keep Mode (EEG)')
        else:
            self.keep_mode = False
            self.setMessage('Keyboard Mode')

    def power_handle_mode_control(self, state):
        if state == QtCore.Qt.Checked:
            self.dashboard.set_power_handle_mode(True)
            self.setMessage('Power Handle (Auto Steering Middle)')
        else:
            self.dashboard.set_power_handle_mode(False)
            self.setMessage('Turn Off Power Handle')

    def ignore_eeg_input_control(self, state):
        if state == QtCore.Qt.Checked:
            self.dashboard.set_ignore_eeg_input(True)
            self.setMessage('Ignore EEG Input')
        else:
            self.dashboard.set_ignore_eeg_input(False)
            self.setMessage('Access EEG Input')

    def stright_control(self, state):
        if state == QtCore.Qt.Checked:
            self.dashboard.set_rc_stright_mode(True)
            self.setMessage('RC STRIGHT Mode')
        else:
            self.dashboard.set_rc_stright_mode(False)
            self.setMessage('RC FREE L/R Mode')

    def __init__(self):
        QWidget.__init__(self)
        self.setWindowTitle("EEG Pilot Dashboard")
        self.setGeometry(0, 0, 750, 800)
        # self.setGeometry(300, 300, 750, 800)
        self.dashboard = EegCarDashboard()
        self.dashboard.set_max_throttle(DEFAULT_MAX_THROTTLE)
        self.dashboard.set_backward_max_throttle(DEFAULT_MAX_BACK_THROTTLE)

        self.layout = QVBoxLayout(self)

        # Drive Setting
        self.rc_mode = QCheckBox('Remote Control', self)
        self.rc_mode.stateChanged.connect(self.remote_control)

        self.rc_stright_mode = QCheckBox('RC Stright', self)
        self.rc_stright_mode.stateChanged.connect(self.stright_control)

        self.keep_mode_checkbox = QCheckBox('Keep Mode', self)
        self.keep_mode_checkbox.stateChanged.connect(self.keep_mode_control)

        self.power_handle_mode_checkbox = QCheckBox('Power Handle', self)
        self.power_handle_mode_checkbox.stateChanged.connect(self.power_handle_mode_control)

        self.ignore_eeg_input = QCheckBox('Ignore Eeg Input', self)
        self.ignore_eeg_input.stateChanged.connect(self.ignore_eeg_input_control)

        drive_layout = QHBoxLayout(self)
        drive_layout.addWidget(self.rc_mode)
        drive_layout.addWidget(self.rc_stright_mode)
        drive_layout.addWidget(self.keep_mode_checkbox)
        drive_layout.addWidget(self.power_handle_mode_checkbox)
        drive_layout.addWidget(self.ignore_eeg_input)

        drive_groupbox = QtGui.QGroupBox("Drive Status & Setting")
        drive_groupbox.setLayout(drive_layout)

        # Throttle Setting
        self.throttle_slider = QSlider(Qt.Horizontal)
        self.throttle_slider.setFocusPolicy(Qt.StrongFocus)
        self.throttle_slider.setTickPosition(QSlider.TicksBothSides)
        self.throttle_slider.setTickInterval(10)
        self.throttle_slider.setSingleStep(10)
        self.throttle_slider.setValue(DEFAULT_MAX_THROTTLE)

        self.throttle_slider.valueChanged.connect(self.throttle_slider.setValue)
        self.connect(self.throttle_slider, SIGNAL("valueChanged(int)"), self.setSliderMaxThrottle)
        self.throttle_label = QLabel('Max Throttle (%): ', self)


        self.maxThrottle = QLineEdit(str(DEFAULT_MAX_THROTTLE))
        # self.maxThrottle.textChanged[str].connect(self.setMaxThrottle)
        self.maxThrottle.editingFinished.connect(self.setMaxThrottle)
        self.maxThrottle.setMaxLength(2)
        self.maxThrottle.setMaximumWidth(40)

        self.backwardMaxThrottle = QLineEdit(str(DEFAULT_MAX_BACK_THROTTLE))
        # self.maxThrottle.textChanged[str].connect(self.setMaxThrottle)
        self.backwardMaxThrottle.editingFinished.connect(self.setBackwardMaxThrottle)
        self.backwardMaxThrottle.setMaxLength(2)
        self.backwardMaxThrottle.setMaximumWidth(40)

        throttle_layout = QHBoxLayout(self)
        throttle_layout.addWidget(self.throttle_label)
        throttle_layout.addWidget(self.throttle_slider)
        throttle_layout.addWidget(QLabel("Forward Max:"))
        throttle_layout.addWidget(self.maxThrottle)

        throttle_layout.addWidget(QLabel("Backward Max:"))
        throttle_layout.addWidget(self.backwardMaxThrottle)

        throttle_groupbox = QtGui.QGroupBox("Max Throttle Setting (30-99)")
        throttle_groupbox.setLayout(throttle_layout)

        # Steering
        self.steering_label = QLabel('Turn Range', self)
        self.steering_turn_range_slider = QSlider(Qt.Horizontal)
        self.steering_turn_range_slider.setFocusPolicy(Qt.StrongFocus)
        self.steering_turn_range_slider.setTickPosition(QSlider.TicksBothSides)
        self.steering_turn_range_slider.setRange(1, 9)
        # self.steering_slider.setMinimum(2)
        # self.steering_slider.setMaximum(8)
        self.steering_turn_range_slider.setMinimum(4)
        self.steering_turn_range_slider.setMaximum(8)
        self.steering_turn_range_slider.setTickInterval(1)
        self.steering_turn_range_slider.setSingleStep(1)
        self.steering_turn_range_slider.setValue(6)
        self.steering_turn_range_slider.valueChanged.connect(self.steering_turn_range_slider.setValue)
        self.connect(self.steering_turn_range_slider, SIGNAL("valueChanged(int)"), self.setSteeringTurnRangeValue)

        self.steering_adjust_label = QLabel(' Home Adjust ', self)
        self.steering_move_left_button = QPushButton('<Left+', self)
        self.steering_current_pos = QLabel('0', self)
        self.steering_move_right_button = QPushButton('-Right>', self)

        self.steering_move_ticks = QLineEdit(str(5000))
        self.steering_move_ticks.editingFinished.connect(self.set_steering_move_ticks_value)
        self.steering_move_ticks.setMaxLength(5)
        self.steering_move_ticks.setMaximumWidth(50)

        self.steering_reset = QPushButton('Reset', self)

        self.steering_move_left_button.clicked.connect(self.steering_move_left)
        self.steering_move_right_button.clicked.connect(self.steering_move_right)
        self.steering_reset.clicked.connect(self.steering_reset_position)

        steering_layout = QHBoxLayout(self)
        steering_layout.addWidget(self.steering_label)
        # steering_layout.addWidget(self.steering_slider)
        steering_layout.addWidget(self.steering_turn_range_slider)
        steering_layout.addWidget(self.steering_adjust_label)
        steering_layout.addWidget(self.steering_move_left_button)


        steering_layout.addWidget(self.steering_current_pos)
        steering_layout.addWidget(self.steering_move_right_button)
        steering_layout.addWidget(self.steering_move_ticks)
        steering_layout.addWidget(self.steering_reset)

        steering_groupbox = QtGui.QGroupBox("Steering Setting")
        steering_groupbox.setLayout(steering_layout)

        self.layout.addWidget(self.dashboard, 2)
        self.layout.addWidget(drive_groupbox)
        self.layout.addWidget(throttle_groupbox)
        self.layout.addWidget(steering_groupbox)

        self.statusBar = QStatusBar()
        self.statusBar.showMessage('Ready', 2000)
        self.layout.addWidget(self.statusBar)

        self.setIcon()
        self.show()

        # save the state
        self.default_backgroundcolor = self.palette().color(QtGui.QPalette.Background)
        self.previos_steering = 50
        self.init_keep_mode()
        self.init_power_handle_mode()

        # Timer For reading current steering position
        # self.timer = QtCore.QTimer()
        # self.timer.timeout.connect(self.readSteeringPos)
        # # check every second
        # self.timer.start(1000)  

        # Timer For Powerhandle
        # self.power_handle_timer = QtCore.QTimer()
        # self.power_handle_timer.timeout.connect(self.update_power_handle)
        # # check every half second
        # self.power_handle_timer.start(500)

        # # Timer For Start Accel
        # self.start_accel_timer = QtCore.QTimer()
        # # self.start_accel_timer.singleShot(5000, self.end_start_accel_handle)
        # self.can_start_accel = True

    # def set_start_accel(self, value):
    #     self.can_start_accel = value

    # def get_start_accel(self):
    #     return self.can_start_accel

    # def end_start_accel_handle(self):
    #     self.dashboard.end_start_accel()

    # def update_power_handle(self):
    #     if self.power_handle_mode:
    #         self.dashboard.update_power_handle()

    def readSteeringPos(self):
        # self.setMessage(str(self.dashboard.steering.get_current_steering()))
        # TODO: is it thread safe?
        # self.steering_set_current_pos(self.dashboard.steering.get_current_location())
        return

    def getMaxThrottle(self):
        return int(self.maxThrottle.text())

    def getBackwardMaxThrottle(self):
        return int(self.backwardMaxThrottle.text())

    def setMaxThrottle(self, _throttle=None):
        if _throttle is None: # from line textbox
            throttle = self.getMaxThrottle()
            self.throttle_slider.blockSignals(True); # update slider
            self.throttle_slider.setValue(throttle);
            self.throttle_slider.blockSignals(False);
        else: # from slider 
            throttle = _throttle
            self.maxThrottle.blockSignals(True); # update line edit
            self.maxThrottle.setText(str(throttle)) 
            self.maxThrottle.blockSignals(False);
            self.maxThrottle.setModified(True)

        if self.maxThrottle.isModified():
            if throttle >= FORWARD_THROTTLE_THRESHOLD: # forward throttle threshold is 20
                self.dashboard.set_max_throttle(throttle)
                self.setMessage("Forward Max Throttle: %d" % throttle)
                self.maxThrottle.clearFocus()
        self.maxThrottle.setModified(False)

    def setBackwardMaxThrottle(self):
        throttle = self.getBackwardMaxThrottle()
        if self.backwardMaxThrottle.isModified():
            if throttle >= BACKWARD_THROTTLE_THRESHOLD: # backward throttle threshold is 20
                self.dashboard.set_backward_max_throttle(throttle)
                self.backwardMaxThrottle.clearFocus()
        self.backwardMaxThrottle.setModified(False)

    def setIcon(self):
        self.appIcon = QIcon('logo.png')
        self.setWindowIcon(self.appIcon)

    def init_keep_mode(self):
        self.w_keep_countdown = 0
        self.x_keep_countdown = 0
        self.a_keep_countdown = 0
        self.d_keep_countdown = 0
        self.default_keep_countdown = DEFAULT_KEEP_COUNT
        # self.default_keep_countdown = 28
        # self.default_keep_countdown = 38
        self.keep_mode = False

    def init_power_handle_mode(self):
        self.power_handle_mode = False

    def is_keep_mode(self, ignore_key):
        # if key is 'w' -> w_keep_countdown
        # if key is 'x' -> x_keep_countdown
        # ignore several 's' key while chountdown number to zero

        if self.keep_mode:
            if ignore_key == Qt.Key_S: 
                if self.dashboard.power_handle_mode == True:
                    self.dashboard.update_power_handle()
                if self.w_keep_countdown > 0:
                    self.w_keep_countdown = self.w_keep_countdown - 1
                    # print "w keep countdown %d" % self.w_keep_countdown
                    self.setMessage("w keep countdown %d" % self.w_keep_countdown)
                    self.x_keep_countdown = 0
                    return True
                if self.x_keep_countdown > 0:
                    self.x_keep_countdown = self.x_keep_countdown - 1
                    # print "x keep countdown %d" % self.x_keep_countdown
                    self.setMessage("x keep countdown %d" % self.x_keep_countdown)
                    self.w_keep_countdown = 0
                    return True
 
            if ignore_key == Qt.Key_X: 
                if self.w_keep_countdown > 0:
                    self.w_keep_countdown = self.w_keep_countdown - 1
                    self.setMessage("w keep countdown %d" % self.w_keep_countdown)
                    if self.w_keep_countdown < DEFAULT_KEEP_COUNT - 10:
                      # self.stop()
                      self.dashboard.set_key_input('s')
                      self.dashboard.stop()
                      self.dashboard.set_start_accel(True)
                    return True

            if ignore_key == Qt.Key_W: 
                if self.x_keep_countdown > 0:
                    self.x_keep_countdown = self.x_keep_countdown - 1
                    self.setMessage("x keep countdown %d" % self.x_keep_countdown)
                    if self.x_keep_countdown < DEFAULT_KEEP_COUNT - 10:
                      # self.stop()
                      self.dashboard.set_key_input('s')
                      self.dashboard.stop()
                      self.dashboard.set_start_accel(True)
                    return True
 
        return False

    def go_to_keep_mode(self, key):
        if key == Qt.Key_W:
            self.w_keep_countdown = self.default_keep_countdown

        if key == Qt.Key_X:
            self.x_keep_countdown = self.default_keep_countdown

        # A, D make a w_keep_countdown FOR powerhandle
        if key == Qt.Key_A:
            self.w_keep_countdown = self.default_keep_countdown

        if key == Qt.Key_D:
            self.w_keep_countdown = self.default_keep_countdown
                
    def keyPressEvent(self, event):
        if self.dashboard.rc_mode == True :
            if self.dashboard.ignore_eeg_input == True:
                self.ignore_eeg_input.setChecked(True)
                if event.key():
                    self.dashboard.set_key_input('Ignore')
                return
            else: 
                self.ignore_eeg_input.setChecked(False)

        # self.update_power_handle(event.key())

        if self.is_keep_mode(event.key()):
            return

        if event.key() == Qt.Key_S:
            self.dashboard.set_key_input('s')
            self.dashboard.stop()
            self.dashboard.set_start_accel(True)

        if event.key() == Qt.Key_W:
            self.dashboard.set_key_input('w')
            if self.dashboard.get_start_accel() == True:
                self.dashboard.start_accel_forward()
            else:
                self.dashboard.forward()

        if event.key() == Qt.Key_A:
            self.dashboard.set_key_input('a')
            if self.dashboard.get_start_accel() == True:
                self.dashboard.start_accel_turn_left()
            else:
                self.dashboard.turn_left()

        if event.key() == Qt.Key_X:
            self.dashboard.set_key_input('x')

            if self.dashboard.get_start_accel() == True:
                self.dashboard.start_accel_backward()
            else:
                self.dashboard.backward()

        if event.key() == Qt.Key_D:
            self.dashboard.set_key_input('d')
            if self.dashboard.get_start_accel() == True:
                self.dashboard.start_accel_turn_right()
            else:
                self.dashboard.turn_right()

        if event.key() == Qt.Key_B:
            self.dashboard.set_key_input('b')
            self.dashboard.brake()

        if event.key() == Qt.Key_R:
            self.dashboard.set_key_input('r')
            # TODO: Make Inspection Mode
            # self.dashboard.steering.position_clear()
            #pot = self.dashboard.wheel.get_steering_pot()
            #self.dashboard.steering.middle_position(pot)

        if event.key() == Qt.Key_F:
            if self.dashboard.isFullScreen():
                for i in range(self.layout.count()):
                    w = self.layout.itemAt(i).widget()
                    w.show()
                self.dashboard.showNormal()
                self.change_backgroundcolor(self.default_backgroundcolor);
                self.setWindowFlags(QtCore.Qt.Window | QtCore.Qt.WindowTitleHint)
                self.showNormal()
            else:
                for i in range(self.layout.count()):
                    w = self.layout.itemAt(i).widget()
                    if w == self.dashboard:
                        continue
                    w.hide()
                self.change_backgroundcolor(Qt.black);
                self.setWindowFlags(QtCore.Qt.Window | QtCore.Qt.FramelessWindowHint)
                self.showMaximized()
                self.dashboard.showFullScreen()

            self.dashboard.reset_label_position()

        if event.key() == Qt.Key_Escape:
            self.dashboard.close()
            self.close()

        self.go_to_keep_mode(event.key())

    def change_backgroundcolor(self, color):
        p = self.palette()
        p.setColor(self.backgroundRole(), color)
        self.setPalette(p)
Ejemplo n.º 27
0
class MainWindow(QMainWindow):
	"""docstring for MainWindow"""
	def __init__(self):
		super(MainWindow,self).__init__()
		self.initGui()

	def initGui(self):
		self.setWindowTitle('Aeneid Text Editor')
		self.setWindowIcon(QIcon())
		self.setGeometry(300,300, 400,300)
		self.setupComponents()
		self.show()

	def setupComponents(self):
		""" Function to setup status bar, central widget
			and menu bar
		"""
		self.myStatusBar = QStatusBar()
		self.setStatusBar(self.myStatusBar)
		self.myStatusBar.showMessage('Ready', 10000)
		self.textEdit=QTextEdit()
		self.setCentralWidget(self.textEdit)

		# 
		self.createActions()
		self.createMenus()

		#
		self.fileMenu.addAction(self.newAction)
		self.fileMenu.addSeparator()
		self.fileMenu.addAction(self.exitAction)
		self.fileMenu.addSeparator()
		self.editMenu.addAction(self.copyAction)
		self.editMenu.addSeparator()
		self.editMenu.addAction(self.pasteAction)
		self.helpMenu.addAction(self.aboutAction)

	# slots called when the menu actions are triggered
	def newFile(self):
		self.textEdit.setText('Aeneid Applicatioon')

	def exitFile(self):
		self.close()

	def aboutHelp(self):
		QMessageBox.about( self, 
						   "About Simple Text Editor", 
						   "Demonstrate use of menu bar")

	def createActions(self):
		""" Function to create actions for menus
		"""
		self.newAction=QAction( QIcon(), '&New', 
								self, 
								shortcut=QKeySequence.New, 
								statusTip="Create a New file" )
		self.exitAction=QAction( QIcon(), '&Exit',
								 self,
								 shortcut="Ctrl+Q",
								 statusTip="Exit the application",
								 triggered=self.exitFile )
		self.copyAction=QAction( QIcon(), '&Copy',
								 self,
								 shortcut="Ctrl+C",
								 statusTip="Copy",
								 triggered=self.textEdit.copy )
		self.pasteAction=QAction( QIcon(), '&Paste',
								  self,
								  shortcut="Ctrl+V",
								  triggered=self.textEdit.paste)
		self.aboutAction=QAction( QIcon(), '&About',
								  self,
								  statusTip="Displays info",
								  triggered=self.aboutHelp )

	# Actual menu bar item creation
	def createMenus(self):
		""" Function to create actual menu bar
		"""
		self.fileMenu = self.menuBar().addMenu("&File")
		self.editMenu = self.menuBar().addMenu("&Edit")
		self.helpMenu = self.menuBar().addMenu("&Help")
Ejemplo n.º 28
0
class MainWindow(QMainWindow):
    def __init__(self, datta):
        QMainWindow.__init__(self)
        self.setWindowTitle('Project Parser')
        appIcon = QIcon('search.png')
        self.setWindowIcon(appIcon)
        self.viewPortBL = QDesktopWidget().availableGeometry().topLeft()
        self.viewPortTR = QDesktopWidget().availableGeometry().bottomRight()
        self.margin = int(QDesktopWidget().availableGeometry().width()*0.1/2)
        self.shirina = QDesktopWidget().availableGeometry().width() - self.margin*2
        self.visota = QDesktopWidget().availableGeometry().height() - self.margin*2
        self.setGeometry(self.viewPortBL.x() + self.margin, self.viewPortBL.y() + self.margin,
                         self.shirina, self.visota)
        # statusbar
        self.myStatusBar = QStatusBar()
        self.setStatusBar(self.myStatusBar)
        
        #lower long layout
        self.lowerLong = QFrame()
        self.detailsLabel = QLabel()
        self.skillsLabel = QLabel()
        self.urlLabel = QLabel()
        self.locationLabel = QLabel()
        self.skillsLabel.setText('skills')
        self.detailsLabel.setWordWrap(True)
        self.la = QVBoxLayout()
        self.la.addWidget(self.detailsLabel)
        self.la.addWidget(self.skillsLabel)
        self.la.addWidget(self.urlLabel)
        self.la.addWidget(self.locationLabel)
        self.lowerLong.setLayout(self.la)

        # table
        self.source_model = MyTableModel(self, datta, ['Id', 'Date', 'Title'])
        self.proxy_model = myTableProxy(self)
        self.proxy_model.setSourceModel(self.source_model)
        self.proxy_model.setDynamicSortFilter(True)
        self.table_view = QTableView()
        self.table_view.setModel(self.proxy_model)
        self.table_view.setAlternatingRowColors(True)
        self.table_view.resizeColumnsToContents()
        self.table_view.resizeRowsToContents()
        self.table_view.horizontalHeader().setStretchLastSection(True)
        self.table_view.setSortingEnabled(True)
        self.table_view.sortByColumn(2, Qt.AscendingOrder)

        # events
        self.selection = self.table_view.selectionModel()
        self.selection.selectionChanged.connect(self.handleSelectionChanged)
        #DO NOT use CreateIndex() method, use index()
        index = self.proxy_model.index(0,0)
        self.selection.select(index, QItemSelectionModel.Select)
        
        self.upperLong = self.table_view  

        # right side widgets
        self.right = QFrame()
        self.la1 = QVBoxLayout()
        self.btnDownload = QPushButton('Download data')
        self.btnDownload.clicked.connect(self.download)
        self.myButton = QPushButton('Show Skillls')
        self.myButton.clicked.connect(self.showAllSkills)
        self.btnSearchByWord = QPushButton('Search by word(s)')
        self.btnSearchByWord.clicked.connect(self.onSearchByWord)
        self.btnResetFilter= QPushButton('Discard Filter')
        self.btnResetFilter.clicked.connect(self.discardFilter)
        self.btnCopyURL = QPushButton('URL to Clipboard')
        self.btnCopyURL.clicked.connect(self.copyToClipboard)
        self.btnExit = QPushButton('Exit')
        self.btnExit.clicked.connect(lambda: sys.exit())
        self.dateTimeStamp = QLabel()
        self.la1.addWidget(self.btnDownload)
        self.la1.addSpacing(10)
        self.la1.addWidget(self.myButton)
        self.la1.addSpacing(10)
        self.la1.addWidget(self.btnSearchByWord)
        self.la1.addSpacing(10)
        self.la1.addWidget(self.btnResetFilter)
        self.la1.addSpacing(10)
        self.la1.addWidget(self.btnCopyURL)
        self.la1.addSpacing(70)
        self.la1.addWidget(self.btnExit)
        self.la1.addStretch(stretch=0)
        self.la1.addWidget(self.dateTimeStamp)
        self.right.setLayout(self.la1)
        self.right.setFrameShape(QFrame.StyledPanel)

        # splitters
        self.horiSplit = QSplitter(Qt.Vertical)
        self.horiSplit.addWidget(self.upperLong)
        self.horiSplit.addWidget(self.lowerLong)
        self.horiSplit.setSizes([self.visota/2, self.visota/2])
        self.vertiSplit = QSplitter(Qt.Horizontal)
        self.vertiSplit.addWidget(self.horiSplit)
        self.vertiSplit.addWidget(self.right)
        self.vertiSplit.setSizes([self.shirina*3/4, self.shirina*1/4])
        self.setCentralWidget(self.vertiSplit)
        
        self.settings = QSettings('elance.ini', QSettings.IniFormat)
        self.settings.beginGroup('DATE_STAMP')
        self.dateTimeStamp.setText('Data actuality: %s' % self.settings.value('date/time'))
        self.settings.endGroup()
        self.statusText = ''

    def handleSelectionChanged(self, selected, deselected):
        for index in selected.first().indexes():
            #print('Row %d is selected' % index.row())
            ind = index.model().mapToSource(index)
            desc = ind.model().mylist[ind.row()]['Description']
            self.detailsLabel.setText(desc)
            skills = ', '.join(ind.model().mylist[ind.row()]['Skills']).strip()
            self.skillsLabel.setText(skills)
            url = ind.model().mylist[ind.row()]['URL']
            self.urlLabel.setText(url)
            location = ind.model().mylist[ind.row()]['Location']
            self.locationLabel.setText(location)
    
    def showAllSkills(self):
        listSkills = []
        for elem in self.source_model.mylist:
            listSkills += elem['Skills']
        allSkills = Counter(listSkills)
        tbl = MyTableModel(self, allSkills.items(), ['Skill', 'Freq'])
        win = skillsWindow(tbl, self.table_view)
        win.exec_()
    
    def discardFilter(self):
        self.table_view.model().emit(SIGNAL("modelAboutToBeReset()"))
        self.table_view.model().criteria = {}
        self.table_view.model().emit(SIGNAL("modelReset()"))
        self.table_view.resizeRowsToContents()
        
    def download(self):
        self.btnDownload.setDisabled(True)
        self.statusLabel = QLabel('Connecting')
        self.progressBar = QProgressBar()
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(100)
        self.myStatusBar.addWidget(self.statusLabel, 2)
        self.myStatusBar.addWidget(self.progressBar, 1)
        self.progressBar.setValue(1)
        self.settings.beginGroup('URLS')
        initialLink = self.settings.value('CategoriesDetailed/VahaSelected/InitialLink')
        pagingLink = self.settings.value('CategoriesDetailed/VahaSelected/PagingLink')
        self.settings.endGroup()
        downloader = Downloader(initialLink, pagingLink, 25, 5)
        downloader.messenger.downloadProgressChanged.connect(self.onDownloadProgressChanged)
        downloader.messenger.downloadComplete.connect(self.onDownloadComplete)
        downloader.download()
    
    def onDownloadComplete(self):
        #QMessageBox.information(self, 'Download complete', 'Download complete!', QMessageBox.Ok)
        self.table_view.model().emit(SIGNAL("modelAboutToBeReset()"))
        self.settings.beginGroup('DATE_STAMP')
        self.settings.setValue('date/time', time.strftime('%d-%b-%Y, %H:%M:%S'))
        self.dateTimeStamp.setText('Data actuality: %s' % self.settings.value('date/time'))
        self.settings.endGroup()
        with open("elance.json") as json_file:
            jobDB = json.load(json_file)
        for elem in jobDB:
            words = nltk.tokenize.regexp_tokenize(elem['Title'].lower(), r'\w+')
            elem['Tokens'] = words
            elem['Skills'] = [t.strip() for t in elem['Skills'].split(',')]
        self.source_model.mylist = jobDB
        self.table_view.model().emit(SIGNAL("modelReset()"))
        self.btnDownload.setEnabled(True)
        self.myStatusBar.removeWidget(self.statusLabel)
        self.myStatusBar.removeWidget(self.progressBar)
        self.myStatusBar.showMessage(self.statusText, timeout = 5000)
                
    
    def onDownloadProgressChanged(self, stata):
        self.progressBar.setValue(stata[2])
        #text = 'Processed records{:5d} of{:5d}'.format(percentage[0], percentage[1])
        bajtikov = '{:,}'.format(stata[5])
        self.statusText = 'Processed page{:4d} of{:4d}. \
               Job entries{:5d} of{:5d}. \
               Downloaded{:>12s} Bytes'.format(stata[3], stata[4],
                                              stata[0], stata[1],
                                              bajtikov)
        self.statusLabel.setText(self.statusText)
        
    def copyToClipboard(self):
        clipboard = QApplication.clipboard()
        clipboard.setText(self.urlLabel.text())
        self.myStatusBar.showMessage(self.urlLabel.text(), timeout = 3000)
    
    def onSearchByWord(self):
        text, ok = QInputDialog.getText(self, 'Search the base by word(s)', 'Enter your keyword/phrase to search for:')
        if ok:
            words = [t.strip() for t in nltk.tokenize.regexp_tokenize(text.lower(), r'\w+')]
            self.table_view.model().emit(SIGNAL("modelAboutToBeReset()"))
            self.table_view.model().criteria = {'Description' : words}
            self.table_view.model().emit(SIGNAL("modelReset()"))
Ejemplo n.º 29
0
    def __init__(self):
        super(MyMDIApp, self).__init__()

        self.setGeometry(50, 40, 1200, 960)
        # self.setAcceptDrops(True)

        self.filelist = []

        # ====================================
        # UIの生成
        # ====================================
        # :: MDIワークスペースのインスタンス化
        self.workspace = QWorkspace()
        self.workspace.setWindowTitle("Simple WorkSpace Exmaple")

        # :: lite_listview
        self.lite_listview = LiteListView()
        self.lite_listview.addItems(["abc", "def", "ghi", "jkl"])
        self.lite_listview.resize(150, 300)
        self.workspace.addWindow(self.lite_listview)

        # :: ボタンs
        layout = QHBoxLayout()
        self.btn_ana = QPushButton("Analysis")
        self.btn_plot = QPushButton("Plot")
        self.btn_save = QPushButton("Save")
        layout.addWidget(self.btn_ana)
        layout.addWidget(self.btn_plot)
        layout.addWidget(self.btn_save)
        self.btn_wid = QWidget()
        self.btn_wid.setWindowTitle("Feauters Analysis")
        self.btn_wid.setLayout(layout)
        self.workspace.addWindow(self.btn_wid)

        # :: Figure.FigureImapctAndHarmonic
        # : FIH用FigureCanvasグラフオブジェクト
        self.fig_impandharm = FigureImapctAndHarmonic()
        self.fig_impandharm.setWindowTitle("Figure Impact & Harmonic")
        self.workspace.addWindow(self.fig_impandharm)
        self.fig_impandharm.close()

        # : 以下コントローラ
        layout2 = QHBoxLayout()
        self.fih_label = QLabel()
        self.fih_label.setText(self.tr("Impact & Harm"))
        self.fih_btn_ana = QPushButton("Analysis")
        self.fih_btn_plot = QPushButton("Plot")
        self.fih_btn_save = QPushButton("Save")
        layout2.addWidget(self.fih_label)
        layout2.addWidget(self.fih_btn_ana)
        layout2.addWidget(self.fih_btn_plot)
        layout2.addWidget(self.fih_btn_save)
        self.btn_wid2 = QWidget()
        self.btn_wid2.setWindowTitle("Imapct & Harm")
        self.btn_wid2.setLayout(layout2)
        self.workspace.addWindow(self.btn_wid2)

        self.fih_btn_ana.clicked.connect(self.run_FIH_analysis)
        self.fih_btn_plot.clicked.connect(self.run_FIH_plot)
        self.fih_btn_save.clicked.connect(self.fig_impandharm.save)


        # :: キャンバス
        self.sig_canvas = SignalDataCanvas()
        # self.sig_canvas.setWindowTitle(self.tr(u"特徴量グラフ"))
        self.sig_canvas.setWindowTitle(u"特徴量グラフ")
        self.workspace.addWindow(self.sig_canvas)
        self.sig_canvas.close()

        # :: ステータスバー
        self.myStatusBar = QStatusBar()
        self.setStatusBar(self.myStatusBar)
        self.myStatusBar.showMessage('Ready', 1000)
        # :: プログラスバー
        self.progressBar = QProgressBar()
        self.myStatusBar.addPermanentWidget(self.progressBar)
        self.progressBar.reset()
        self.progressBar.setVisible(False)
        self.progressBar.setValue(0)

        # :: MainWidgetに追加
        # self.workspace.tile()
        self.setCentralWidget(self.workspace)
        self.setCSS()

        # ====================================
        # シグナルスロットのコネクト
        # ====================================
        # lite_listview
        self.lite_listview.fileDropped.connect(self.set_filelist)
        self.lite_listview.clicked.connect(self.file_selected)
        # Analysisボタンで解析実行
        self.btn_ana.clicked.connect(self.run_analysis)
        self.btn_plot.clicked.connect(self.run_plot)
Ejemplo n.º 30
0
class CC_window(QWidget):
    def __init__(self):
        super(CC_window, self).__init__()
        self.version = '0.2'
        glo = QVBoxLayout(self)
        self.Runningo = None
        self.Looping = None
        self.P = CC_thread()
        if name == 'nt':
            ficon = r_path('images\\favicon.png')
            licon = r_path('images\\logo.png')
        else:
            ficon = r_path('images/favicon.png')
            licon = r_path('images/logo.png')
        self.tf = QFont("", 13, QFont.Bold)
        self.sf = QFont("", 10, QFont.Bold)
        self.SelfIinit(QIcon(ficon))
        self.center()
        self.a_btn(licon, glo)
        self.ss_btns(glo)
        self.i_list(glo)
        self.cl_btn(glo)
        self.l_btns(glo)
        self.f_btns(glo)
        self.ds_bar(glo)
        self.setLayout(glo)
        self.activateWindow()
        self.show()

    def SelfIinit(self, icon):
        self.setWindowTitle('chrome-cut ' + self.version)
        self.setGeometry(300, 300, 200, 150)
        self.setMinimumWidth(600)
        self.setMaximumWidth(600)
        self.setMinimumHeight(500)
        self.setMaximumHeight(500)
        # Setting Icon
        self.setWindowIcon(icon)
        QToolTip.setFont(self.sf)

    def msgApp(self, title, msg):
        uinfo = QMessageBox.question(self, title, msg,
                                     QMessageBox.Yes | QMessageBox.No)
        if uinfo == QMessageBox.Yes:
            return 'y'
        if uinfo == QMessageBox.No:
            return 'n'

    def closeEvent(self, event=None):
        if self.P.isRunning():
            response = self.msgApp("Making sure",
                                   "Sure, you want to exit while looping ?")
            if response == 'y':
                if event is not None:
                    event.accept()
                self.P.stop()
                exit(0)
            else:
                if event is not None:
                    event.ignore()
        else:
            if event is not None:
                event.accept()
            exit(0)

    def center(self):
        qrect = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qrect.moveCenter(cp)
        self.move(qrect.topLeft())

    def a_btn(self, icon, glo):
        def show_about():
            Amsg = "<center>All credit reserved to the author of chrome-cut "
            Amsg += " version " + self.version
            Amsg += ", This work is a free, open-source project licensed "
            Amsg += " under Mozilla Public License version 2.0 . <br><br>"
            Amsg += " visit us for more infos and how-tos :<br> "
            Amsg += "<b><a href='https://github.io/mrf345/chrome-cut'> "
            Amsg += "https://github.io/mrf345/chrome-cut </a> </b></center>"
            Amsgb = "About chrome-cut"
            return QMessageBox.about(self, Amsgb, Amsg)

        self.abutton = QPushButton('', self)
        self.abutton.setIcon(QPixmap(icon))
        self.abutton.setIconSize(QSize(500, 100))
        self.abutton.setToolTip('About chrome-cut')
        self.abutton.clicked.connect(show_about)
        glo.addWidget(self.abutton)

    def ss_btns(self, glo):
        self.lebutton = QPushButton('Scan IP address', self)
        self.lebutton.setToolTip(
            'Insert and check if a specific IP is a valid chrome cast')
        self.lebutton.setFont(self.tf)
        self.lebutton.clicked.connect(self.sip_input)
        glo.addWidget(self.lebutton)

    def sip_input(self):
        self.lebutton.setEnabled(False)
        self.s_bar.setStyleSheet(self.s_norm)
        self.s_bar.showMessage('> Checking out the IP ..')
        msg = "<center>Enter suspected IP to check : <br><i><u>Usually it is "
        msg += "on 192.168.what_have_you.188</i></center>"
        text, okPressed = QInputDialog.getText(self, "Scan IP", msg)
        if okPressed and text != '':
            self.setCursor(Qt.BusyCursor)
            ch = is_ccast(text)
            if ch:
                self.il_add([text])
                self.unsetCursor()
                self.lebutton.setEnabled(True)
                return True
            else:
                self.s_bar.setStyleSheet(self.s_error)
                self.s_bar.showMessage(
                    '! Error: inserted IP is not chrome cast device')
                self.unsetCursor()
                self.lebutton.setEnabled(True)
                return True
        self.s_bar.clearMessage()
        self.lebutton.setEnabled(True)
        return True

    def i_list(self, glo):
        self.ci_list = QListWidget()
        self.ci_list.setToolTip("List of discovered devices")
        self.ci_list.setEnabled(False)
        self.setFont(self.sf)
        glo.addWidget(self.ci_list)

    def cl_btn(self, glo):
        self.cle_btn = QPushButton('Clear devices list')
        self.cle_btn.setToolTip("Remove all devices from the list")
        self.cle_btn.setFont(self.sf)
        self.cle_btn.setEnabled(False)
        self.cle_btn.clicked.connect(self.il_add)
        glo.addWidget(self.cle_btn)

    def l_btns(self, glo):
        hlayout = QHBoxLayout()
        self.llo = QCheckBox("Looping")
        self.llo.setToolTip(
            'Automate repeating the smae command on the smae device selected ')
        self.llo.setEnabled(False)
        self.nlo = QLineEdit()
        self.nlo.setPlaceholderText("duration in seconds. Default is 10")
        self.nlo.setEnabled(False)
        self.nlo.setToolTip("Duration of sleep after each loop")
        self.lbtn = QPushButton('Stop')
        self.lbtn.setEnabled(False)
        self.lbtn.setFont(self.tf)
        self.llo.setFont(self.sf)
        self.lbtn.setToolTip("stop on-going command or loop")
        self.llo.toggled.connect(self.loped)
        self.lbtn.clicked.connect(partial(self.inloop_state, out=True))
        hlayout.addWidget(self.llo)
        hlayout.addWidget(self.nlo)
        hlayout.addWidget(self.lbtn)
        glo.addLayout(hlayout)

    def loped(self):
        if self.Looping:
            self.Looping = None
            self.llo.setChecked(False)
            self.nlo.setEnabled(False)
        else:
            self.Looping = True
            self.llo.setChecked(True)
            self.nlo.setEnabled(True)
        return True

    def f_btns(self, glo):
        hlayout = QHBoxLayout()
        self.ksbutton = QPushButton('Kill stream', self)
        self.ksbutton.setToolTip('Kill whetever been streamed')
        self.ksbutton.setFont(self.tf)
        self.ksbutton.clicked.connect(self.k_act)
        self.sbutton = QPushButton('Stream', self)
        self.sbutton.setFont(self.tf)
        self.sbutton.setToolTip('Stream a youtube video')
        self.fbutton = QPushButton('Factory reset', self)
        self.fbutton.setFont(self.tf)
        self.fbutton.setToolTip('Factory reset the device')
        self.fbutton.clicked.connect(self.fr_act)
        self.sbutton.clicked.connect(self.yv_input)
        self.ksbutton.setEnabled(False)
        self.sbutton.setEnabled(False)
        self.fbutton.setEnabled(False)
        hlayout.addWidget(self.ksbutton)
        hlayout.addWidget(self.sbutton)
        hlayout.addWidget(self.fbutton)
        glo.addLayout(hlayout)

    def ch_dur(th=None, dur=10):
        if len(dur) >= 1:
            try:
                dur = int(dur)
            except:
                dur = None
            if dur is None or not isinstance(dur, int):
                self.s_bar.setStyleSheet(self.s_error)
                self.s_bar.showMessage(
                    '! Error: wrong duration entery, only integers')
                return None
        else:
            dur = 10
        return dur

    def k_act(self):
        if self.ci_list.count() >= 1:
            cr = self.ci_list.currentRow()
            if cr is None or cr <= 0:
                cr = 0
            ip = self.ci_list.item(cr).text()
            if self.Looping is not None:
                dur = self.ch_dur(self.nlo.text())
                if dur is None:
                    return True
                self.P = CC_thread(cancel_app, dur, ip)
                self.P.start()
                self.P.somesignal.connect(self.handleStatusMessage)
                self.P.setTerminationEnabled(True)
                self.inloop_state()
                return True
            else:
                ch = cancel_app(ip)
                if ch is None:
                    self.s_bar.setStyleSheet(self.s_error)
                    self.s_bar.showMessage('! Error: failed to kill stream ..')
                else:
                    self.s_bar.setStyleSheet(self.s_norm)
                    self.s_bar.showMessage('# Stream got killed ')
        else:
            self.s_bar.setStyleSheet(self.s_error)
            self.s_bar.showMessage('! Error: No items selected from the list')
            self.eout()
        return True

    def fr_act(self):
        if self.ci_list.count() >= 1:
            cr = self.ci_list.currentRow()
            if cr is None or cr <= 0:
                cr = 0
            ip = self.ci_list.item(cr).text()
            if self.Looping is not None:
                dur = self.ch_dur(self.nlo.text())
                if dur is None:
                    return True
                self.P = CC_thread(reset_cc, dur, ip)
                self.P.start()
                self.P.somesignal.connect(self.handleStatusMessage)
                self.P.setTerminationEnabled(True)
                self.inloop_state()
                return True
            else:
                ch = reset_cc(ip)
                if ch is None:
                    self.s_bar.setStyleSheet(self.s_error)
                    self.s_bar.showMessage(
                        '! Error: failed to factory reset ..')
                else:
                    self.s_bar.setStyleSheet(self.s_norm)
                    self.s_bar.showMessage('# Got factory reseted ')
        else:
            self.s_bar.setStyleSheet(self.s_error)
            self.s_bar.showMessage('! Error: No items selected from the list')
            self.eout()
        return True

    def y_act(self, link=None):
        if self.ci_list.count() >= 1:
            cr = self.ci_list.currentRow()
            if cr is None or cr <= 0:
                cr = 0
            ip = self.ci_list.item(cr).text()
            if self.Looping is not None:
                dur = self.ch_dur(self.nlo.text())
                if dur is None:
                    return True
                self.P = CC_thread(send_app, dur, ip, link)
                self.P.start()
                self.P.somesignal.connect(self.handleStatusMessage)
                self.P.setTerminationEnabled(True)
                self.inloop_state()
                return True
            else:
                ch = reset_cc(ip)
                if ch is None:
                    self.s_bar.setStyleSheet(self.s_error)
                    self.s_bar.showMessage('! Error: failed to stream link ..')
                else:
                    self.s_bar.setStyleSheet(self.s_norm)
                    self.s_bar.showMessage('# Streamed the link ')
        else:
            self.s_bar.setStyleSheet(self.s_error)
            self.s_bar.showMessage('! Error: No items selected from the list')
            self.eout()
        return True

    def yv_input(self):
        text, okPressed = QInputDialog.getText(
            self, "Stream youtube",
            "Enter youtube video link to be streamed :")
        if okPressed and text != '':
            ntext = text.split('?')
            if len(ntext) <= 1:
                self.s_bar.setStyleSheet(self.s_error)
                self.s_bar.showMessage('! Error: Invalid youtube linkd ')
                return False
            ntext = ntext[1]
            if ntext != '' and len(ntext) > 1 and "youtube" in text:
                self.y_act(ntext)
                return True
            else:
                self.s_bar.setStyleSheet(self.s_error)
                self.s_bar.showMessage('! Error: Invalid youtube linkd ')
        return False

    @Slot(object)
    def handleStatusMessage(self, message):
        self.s_bar.setStyleSheet(self.s_loop)
        self.s_bar.showMessage(message)

    def il_add(self, items=[]):
        if len(items) >= 1:
            self.s_bar.setStyleSheet(self.s_norm)
            for i in items:
                fitem = self.ci_list.findItems(i, Qt.MatchExactly)
                if len(fitem) >= 1:
                    self.s_bar.setStyleSheet(self.s_error)
                    self.s_bar.showMessage(
                        '! Error: Device exists in the list')
                else:
                    self.s_bar.setStyleSheet(self.s_norm)
                    self.ci_list.addItem(i)
                    self.s_bar.showMessage('# Device was found and added')
            if not self.P.isRunning():
                self.cle_btn.setEnabled(True)
                self.ci_list.setEnabled(True)
                self.llo.setEnabled(True)
                self.nlo.setEnabled(True)
                self.ksbutton.setEnabled(True)
                self.sbutton.setEnabled(True)
                self.fbutton.setEnabled(True)
        else:
            self.s_bar.setStyleSheet(self.s_norm)
            self.s_bar.showMessage('# Cleard devices list')
            self.ci_list.clear()
            self.cle_btn.setEnabled(False)
            self.ci_list.setEnabled(False)
            self.ksbutton.setEnabled(False)
            self.llo.setEnabled(False)
            self.nlo.setEnabled(False)
            self.sbutton.setEnabled(False)
            self.fbutton.setEnabled(False)
        return True

    def inloop_state(self, out=False):
        if not out:
            self.lbtn.setEnabled(True)
            self.cle_btn.setEnabled(False)
            self.ci_list.setEnabled(False)
            self.ksbutton.setEnabled(False)
            self.llo.setEnabled(False)
            self.nlo.setEnabled(False)
            self.sbutton.setEnabled(False)
            self.fbutton.setEnabled(False)
        else:
            if self.P.isRunning():
                self.P.stop()
            self.lbtn.setEnabled(False)
            self.cle_btn.setEnabled(True)
            self.ci_list.setEnabled(True)
            self.ksbutton.setEnabled(True)
            self.llo.setEnabled(True)
            self.nlo.setEnabled(True)
            self.sbutton.setEnabled(True)
            self.fbutton.setEnabled(True)
            self.s_bar.clearMessage()
        return True

    def ds_bar(self, glo):
        self.s_bar = QStatusBar()
        self.s_error = "QStatusBar{color:red;font-weight:1000;}"
        self.s_loop = "QStatusBar{color:black;font-weight:1000;}"
        self.s_norm = "QStatusBar{color:blue;font-style:italic;"
        self.s_norm += "font-weight:500;}"
        self.s_bar.setStyleSheet(self.s_norm)
        glo.addWidget(self.s_bar)

    def eout(self):
        msgg = "<center>"
        msgg += " Opps, a critical error has occurred, we will be "
        msgg += " grateful if you can help fixing it, by reporting to us "
        msgg += " at : <br><br> "
        msgg += "<b><a href='https://github.io/mrf345/chrome-cut'> "
        msgg += "https://github.io/mrf345/chrome-cut </a></b> </center>"
        mm = QMessageBox.critical(self, "Critical Error", msgg, QMessageBox.Ok)
        exit(0)
Ejemplo n.º 31
0
class mainwin(QMainWindow):
	def __init__(self, parent=None):
		super(mainwin, self).__init__(parent)
		self.setWindowTitle("Nigandu English to Tamil Dictionary")
		self.setGeometry(200, 50, 650, 600)
		self.setMinimumHeight(620)
		self.setMinimumWidth(650)
		self.setMaximumHeight(660)
		self.setMaximumWidth(800)
		#Setting up status bar
		self.myStatusBar = QStatusBar()
		self.myStatusBar.showMessage('Ready', 7000)
		self.setStatusBar(self.myStatusBar)
		#Setting up application icon
		appIcon = QIcon(":/icons/njnlogo.png")
		self.setWindowIcon(appIcon)

		# defining the central widget
		self.central = QWidget(self)

		#combobox plus search button
		self.whole = QVBoxLayout(self.central)
		self.gridlayout = QGridLayout()
		self.comboBox = QLineEdit(self)
		#self.comboBox.setEditable(True)
		self.comboBox.setObjectName("comboBox")
		self.completer = QCompleter(self.comboBox)
		self.completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion)
		self.completer.setCaseSensitivity(Qt.CaseInsensitive)
		self.completer.setMaxVisibleItems(10)
		self.comboBox.setCompleter(self.completer)
		#self.comboBox.setCompleter()
		self.gridlayout.addWidget(self.comboBox, 1, 1, 1, 2)

		self.searchbtn = QPushButton()
		self.searchbtn.setObjectName("searchbtn")
		self.searchbtn.setText("&Search")
		self.gridlayout.addWidget(self.searchbtn, 1, 3)

		vbox = QVBoxLayout()
		self.tamtext = QTextBrowser()
		self.listview = QListWidget(self)
		#self.listview.setEditTriggers(QAbstractItemView.NoEditTriggers)
		self.listview.setWindowTitle("Suggested words")
		self.tamtext.setMinimumHeight(100)
		self.tamtext.setMaximumHeight(150)
		vbox.addWidget(self.tamtext)
		self.suglbl = QLabel(self)
		self.suglbl.setText("Suggested Words:")
		vbox.addWidget(self.suglbl)
		vbox.addWidget(self.listview)

		self.whole.addLayout(self.gridlayout)
		self.whole.addLayout(vbox)
		self.setCentralWidget(self.central)

		#setting docks
		self.histdockwidg = QDockWidget("History", self)
		self.bkmdockwidg = QDockWidget("Book Marks", self)
		self.histdockwidg.setObjectName("self.histdockwidg")
		self.bkmdockwidg.setObjectName("self.bkmdockwidg")

		#self.histdockwidg.setMaximumWidth(histwidth)
		self.histdockwidg.setAllowedAreas(Qt.RightDockWidgetArea)
		self.bkmdockwidg.setAllowedAreas(Qt.RightDockWidgetArea)
		self.histdockwidg.setMaximumWidth(250)
		self.bkmdockwidg.setMaximumWidth(250)
		self.histdockwidg.setMinimumWidth(200)
		self.bkmdockwidg.setMinimumWidth(200)

		#self.bkmdockwidg.setMaximumWidth(histwidth)
		self.histli = QListWidget()
		self.bkmli = QListWidget()
		self.histlis = [0]
		self.bkmlistfromfile = []
		self.histdockwidg.setWidget(self.histli)
		self.bkmdockwidg.setWidget(self.bkmli)
		self.addDockWidget(Qt.RightDockWidgetArea, self.histdockwidg)
		self.addDockWidget(Qt.RightDockWidgetArea, self.bkmdockwidg)

		#file menu
		fi_addwrd = self.createactions("&Add a word...", self.addwrdf, "Alt+A", ":/icons/add.png",
		                               "Add a word to the dictionary. . .")
		fi_options = self.createactions("&Options", self.optionsf, "None", ":/icons/options.png",
		                                "Change the default settings. . .")
		fi_help = self.createactions("&Help", self.helpf, QKeySequence.HelpContents, ":/icons/help.png",
		                             "Help contents. . .")
		fi_quit = self.createactions("&Quit", self.close, QKeySequence.Close, ":/icons/quit.png",
		                             "Close the application. . .")
		fplus = self.createactions("FontPlus", self.fplusf, "None", ":/icons/fplus.png", "Increase the font size")
		fminus = self.createactions("FontMinus", self.fminusf, "None", ":/icons/fminus.png", "Decrease the font size")
		#list of file actions
		fi_menu = (fi_addwrd, fi_options, fi_help, None, fi_quit)

		#go menu
		self.go_prev = self.createactions("&Previous Word", self.prevf, "Alt+Z", ":/icons/prev.png",
		                                  "Previous Word")
		self.go_next = self.createactions("&Next Word", self.nextf, "Alt+X", ":/icons/next.png", "Next Word")
		self.go_rand = self.createactions("&Random Word", self.randf, "Ctrl+R", ":/icons/rand.png",
		                                  "Select a random word")
		#list of go actions
		go_menu = (self.go_prev, self.go_next, self.go_rand )
		self.go_next.setEnabled(False)
		self.go_prev.setEnabled(False)

		#book mark menu
		self.bkm_addfav = self.createactions("&Bookmark", self.addfavf, "Ctrl+B", ":/icons/bookmark.png",
		                                     "Book mark this word")
		self.bkm_viewbkm = self.createactions("&View Bookmarks", self.viewbkmf, "Alt+V", ":/icons/viewbkm.png",
		                                      "View bookmarked words")
		#list of book mark items
		bkm_menu = (self.bkm_addfav, self.bkm_viewbkm)

		#help menu
		hlp_about = self.createactions("Abo&ut", self.aboutf, "Ctrl+U", ":/icons/about.png", "About")
		hlp_visitblog = self.createactions("&Visit Blog", self.visitblogf, "None", ":/icons/visitblog.png",
		                                   "Visit our blog")
		hlp_help = self.createactions("&Help", self.helpf, "Ctrl+H", ":/icons/help.png", "Help Contents")
		#list of help menu items
		hlp_menu = (hlp_about, hlp_visitblog, hlp_help)

		#Setting up the menubar
		filemenu = self.menuBar().addMenu("&File")
		self.addmenu(filemenu, fi_menu)
		gomenu = self.menuBar().addMenu("&Go")
		self.addmenu(gomenu, go_menu)
		bkmmenu = self.menuBar().addMenu("&Book Mark")
		self.addmenu(bkmmenu, bkm_menu)
		helpmenu = self.menuBar().addMenu("&Help")
		self.addmenu(helpmenu, hlp_menu)
		intn = QSize(40, 40)
		self.setIconSize(intn)
		#Setting up the tool bar
		filetools = self.addToolBar("File")
		filetools.setObjectName("filetools")
		self.addmenu(filetools, (fi_addwrd, fplus, fminus))

		gotools = self.addToolBar("Go")
		gotools.setObjectName("gotools")
		self.addmenu(gotools, go_menu)

		bkmtools = self.addToolBar("Bkm")
		bkmtools.setObjectName("bkmtools")
		self.addmenu(bkmtools, bkm_menu)

		hlptools = self.addToolBar("Help")
		hlptools.setObjectName("helptools")
		self.addmenu(hlptools, hlp_menu)

		self.loadfiles()
		self.returncount = 0
		self.bkm_addfav.setEnabled(False)

		#clipboard function
		if self.clipauto:
			clip = QApplication.clipboard()
			cliptxt = clip.text()
			self.comboBox.setText(cliptxt)
			self.setevent()

		#connections
		self.connect(self.comboBox, SIGNAL("textChanged(QString)"), self.search)
		self.connect(self.comboBox, SIGNAL("returnPressed()"), self.returnpressedevent)
		self.connect(self.searchbtn, SIGNAL("clicked()"), self.onenter)
		self.connect(self.listview, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.listwidcall)
		self.connect(self.histli, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.listwidcall)
		self.connect(self.bkmli, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.listwidcall)

	def writehistlis(self, lis):
		if len(lis) >= 2:
			for i in range(1, len(lis)):
				cur.execute("insert into HISTORY values(?)", (lis[i], ))

	def writebkmlis(self, lis):
		cur.execute("delete from BOOKMARKS")
		if len(lis) > 0:
			for i in range(len(lis)):
				cur.execute("insert into BOOKMARKS values(?)", (lis[i], ))

	def listwidcall(self, item):
		self.comboBox.setText(item.text())
		self.setevent()

	def search(self, text, *args):
		li = []
		tplus = text + "%"
		cur.execute("select ENGW from ENGTAM where ENGW like ? limit 20", (tplus, ))
		cuf = cur.fetchall()
		model = QStringListModel()
		for i in range(len(cuf)):
			k = cuf[i][0]
			li.append(k)
		model.setStringList(li)
		self.completer.setModel(model)

	def returnpressedevent(self, *args):
		self.comboBox.selectAll()
		self.returncount += 1
		if self.returncount % 2 == 0:
			self.setevent()
		else:
			self.comboBox.selectAll()

	def setevent(self):
		self.comboBox.selectAll()
		self.bkm_addfav.setEnabled(True)
		lis = []
		eng = self.comboBox.text()
		cur.execute("SELECT rowid, TAMW FROM ENGTAM WHERE ENGW like ? limit 1", (eng,))
		cuf = cur.fetchall()
		if len(cuf) == 0:
			self.tamtext.setText("No words found. . . ")
			self.listview.addItem("No Suggestions. . .")
		else:
			for i in range(len(cuf)):
				tam = cuf[0][1]
				rowid = cuf[0][0]
				self.tamtext.setText(tam)
				if rowid <= 25:
					start = 0
					end = 50
				elif rowid >= 190513:
					start = rowid - 190487
					end = rowid + 190537
				else:
					start = rowid - 25
					end = rowid + 25
				cur.execute("SELECT ENGW FROM ENGTAM WHERE rowid>=? and rowid<=?", (start, end, ))
				cuff = cur.fetchall()
				for i in range(len(cuff)):
					engw = cuff[i][0]
					lis.append(engw)
				if self.listview.count() is not None:
					self.listview.clear()
				self.listview.addItems(lis)
				self.addtoli(eng, self.histlis)
				if self.histlis[0] >= 2:
					self.go_prev.setEnabled(True)
				self.comboBox.setFocus()
				if self.histdock:
					self.histli.addItem(eng)

	def addtoli(self, addw, lis, c=1):
		if len(lis) > 0:
			if type(lis[0]) == int:
				if len(lis) >= 2:
					for i in range(1, len(lis)):
						if lis[i] == addw:
							c = 0
							pass
					if c == 1:
						lis.append(addw)
				else:
					lis.append(addw)
				lis[0] = len(lis) - 1

	def addtobkmli(self, addw, lis, nc=1):
		for i in range(len(lis)):
			if lis[i] == addw:
				nc = 0
				pass
		if nc == 1:
			lis.append(addw)

	def onenter(self, *args):
		self.comboBox.selectAll()
		self.setevent()

	def loadfiles(self):
		self.loadsettings()
		self.loadhistlis()
		self.loadbkm()
		self.setfontsize(int(self.fontsize))
		self.setdocks()


	def setdocks(self):
		ist = str(self.histdock)
		jst = str(self.bkmdock)

		if ist == "False":
			self.removedock(self.histdockwidg)
		else:
			self.adddock(self.histdockwidg)

		if jst == "False":
			self.removedock(self.bkmdockwidg)
		else:
			self.adddock(self.bkmdockwidg)

	def loadsettings(self):
		cur.execute("select * from SETTINGS")
		cuffun = cur.fetchall()
		fn = int(cuffun[0][1])
		self.fontsize = fn
		self.clipauto = cuffun[1][1]
		self.histdock = cuffun[2][1]
		self.savehist = cuffun[3][1]
		self.bkmdock = cuffun[4][1]
		self.delhist = cuffun[5][1]
		self.delbkm = cuffun[6][1]

	def loadhistlis(self):
		histtodockli = []
		cur.execute("select * from HISTORY")
		historyfetch = cur.fetchall()
		for i in range(len(historyfetch)):
				self.addtobkmli(historyfetch[i][0], histtodockli)
		for i in histtodockli:
			self.histli.addItem(i)

	def loadbkm(self):
		cur.execute("select * from BOOKMARKS")
		bkmfetch = cur.fetchall()
		for i in range(len(bkmfetch)):
				self.addtobkmli(bkmfetch[i][0], self.bkmlistfromfile)
		for i in self.bkmlistfromfile:
			self.bkmli.addItem(i)

	def createactions(self, text, slot=None, shortcut="None", icon=None, tip=None, checkable=False,
	                  signal="triggered()"):
		action = QAction(text, self)
		if icon is not None:
			action.setIcon(QIcon(icon))
		if shortcut is not None:
			action.setShortcut(shortcut)
		if tip is not None:
			action.setToolTip(tip)
			action.setStatusTip(tip)
		if slot is not None:
			self.connect(action, SIGNAL(signal), slot)
		if checkable:
			action.setCheckable(True)
		return action

	def addmenu(self, target, actions):
		for action in actions:
			if action is None:
				target.addSeparator()
			else:
				target.addAction(action)

	#Actions
	def addwrdf(self):
		self.dlg = addawrd()
		self.dlg.show()
		self.connect(self.dlg.buttonBox, SIGNAL("rejected()"), self.dlg.close)
		self.connect(self.dlg.buttonBox, SIGNAL("accepted()"), self.addawordtodb)


	def addawordtodb(self):
		eng = self.dlg.lineEdit.text()
		tam = self.dlg.lineEdit_2.text()
		if len(eng) != 0 and len(tam) != 0:
			cur.execute("INSERT INTO ENGTAM(ENGW, TAMW) VALUES(?, ?)", (eng, tam, ))
			self.dlg.close()
			QMessageBox.information(self, "Nigandu Eng -> Tam Dictionary", "Added Successfully. . .")
		else:
			self.dlg.lineEdit.setFocus()
			self.dlg.close()
			QMessageBox.warning(self, "Nigandu Eng -> Tam Dictionary", "Invalid Entry. . .")

	def optionsf(self):
		self.opt = optdlg(self)
		self.opt.spinBox.setProperty("value", int(self.fontsize))
		font = QFont()
		font.setPixelSize(int(self.fontsize))
		self.opt.sampletxt.setFont(font)

		if str(self.clipauto) == "True":
			self.opt.checkclip.setChecked(True)
		elif str(self.clipauto) == "False":
			self.opt.checkclip.setChecked(False)

		if str(self.histdock) == "True":
			self.opt.checkshowhistdock.setChecked(True)
		elif str(self.histdock) == "False":
			self.opt.checkshowhistdock.setChecked(False)

		if str(self.bkmdock) == "True":
			self.opt.checkshowbkmdock.setChecked(True)
		elif str(self.bkmdock) == "False":
			self.opt.checkshowbkmdock.setChecked(False)

		self.opt.show()
		self.connect(self.opt.buttonBox, SIGNAL("accepted()"), self.optok)
		self.connect(self.opt.buttonBox.button(QDialogButtonBox.Apply), SIGNAL("clicked()"), self.optapply)
		self.connect(self.opt.checkdelhist, SIGNAL("stateChanged(int)"), self.deleteallhist)
		self.connect(self.opt.checkshowhistdock, SIGNAL("stateChanged(int)"), self.shownexttime)
		self.connect(self.opt.checkshowbkmdock, SIGNAL("stateChanged(int)"), self.shownexttime)

	def shownexttime(self, i):
		if i == 0:
			pass
		if i == 2:
			QMessageBox.information(self, self.windowTitle(), "Click Apply or Ok \n The Dock window will be added, \n the next time you start the application. . .")

	def optok(self):
		self.optapply()
		self.opt.close()

	def optapply(self):
		self.updatesettings()
		self.applyopt()

	def updatesettings(self):
		self.fontsize = self.opt.spinBox.value()
		self.clipauto = self.opt.checkclip.isChecked()
		self.histdock = self.opt.checkshowhistdock.isChecked()
		self.bkmdock = self.opt.checkshowbkmdock.isChecked()
		self.delhist = self.opt.checkdelhist.isChecked()

		for i, j in [("fontsize", self.fontsize),("clipauto", str(self.clipauto)),("histdock", str(self.histdock)),
		             ("bkmdock", str(self.bkmdock)),("delhist", str(self.delhist))]:
			cur.execute("UPDATE SETTINGS SET setting=? WHERE field=?", (j, i, ))


	def applyopt(self):
		self.loadsettings()
		self.setfontsize(int(self.fontsize))
		if str(self.bkmdock) == "False" or str(self.histdock) == "False":
			self.setdocks()

	def removedock(self, dock):
		self.removeDockWidget(dock)

	def adddock(self, dock):
		self.addDockWidget(Qt.RightDockWidgetArea, dock)

	def deleteallhist(self, i):
		if i == 0:
			pass
		elif i == 2:
			self.histli.clear()
			self.histlis = [0]
			cur.execute("delete from HISTORY")
			QMessageBox.information(self, self.windowTitle(), "All the History Records are deleted. . .")

	def setfontsize(self, i):
		if i >= 8 or i <= 24:
			font = QFont()
			font.setPixelSize(i)
			self.comboBox.setFont(font)
			self.searchbtn.setFont(font)
			self.bkmli.setFont(font)
			self.histli.setFont(font)
			self.listview.setFont(font)
			self.tamtext.setFont(font)

	def helpf(self):
		form = helpform.HelpForm("index.html", self)
		form.show()

	def closeEvent(self, *args, **kwargs):
		self.writehistlis(self.histlis)
		self.writebkmlis(self.bkmlistfromfile)

		for i, j in [("fontsize", int(self.fontsize)),("clipauto", str(self.clipauto)),("histdock", str(self.histdock)),
		             ("bkmdock", str(self.bkmdock)),("delhist", str(self.delhist))]:
			cur.execute("UPDATE SETTINGS SET setting=? WHERE field=?", (j, i, ))

		con.commit()
		con.close()

	def fplusf(self):
		self.fontsize += 1
		if self.fontsize <= 24:
			self.setfontsize(self.fontsize)

	def fminusf(self):
		self.fontsize -= 1
		if self.fontsize >= 10:
			self.setfontsize(self.fontsize)

	def prevf(self):
		pr = self.histlis[0] - 1
		if pr > 1:
			self.comboBox.setText(self.histlis[pr])
			self.setevent()
			self.histlis[0] = pr
			self.go_next.setEnabled(True)
		elif pr == 1:
			self.comboBox.setText(self.histlis[pr])
			self.setevent()
			self.histlis[0] = pr
			self.go_next.setEnabled(True)
			self.go_prev.setEnabled(False)
		else:
			pass

	def nextf(self):
		pr = self.histlis[0] + 1
		if pr < len(self.histlis) - 1:
			self.comboBox.setText(self.histlis[pr])
			self.setevent()
			self.histlis[0] = pr
			self.go_prev.setEnabled(True)
		elif pr == len(self.histlis) - 1:
			self.comboBox.setText(self.histlis[pr])
			self.setevent()
			self.histlis[0] = pr
			self.go_prev.setEnabled(True)
			self.go_next.setEnabled(False)
		else:
			pass

	def randf(self):
		import random

		n = random.randrange(190538)
		cur.execute("select ENGW from ENGTAM where rowid = ?", (n, ))
		cuf = cur.fetchone()
		self.comboBox.setText(cuf[0])
		self.setevent()

	def addfavf(self):
		txt = self.comboBox.text()
		if len(txt) != 0:
			self.addtobkmli(txt, self.bkmlistfromfile)
			self.writetolistwidget(self.bkmlistfromfile, self.bkmli)


	def sortit(self):
		self.bkmlistfromfile.sort()
		self.writetolistwidget(self.bkmlistfromfile, self.form.listWidget)
		self.writetolistwidget(self.bkmlistfromfile, self.bkmli)
		cur.execute("delete from BOOKMARKS")


	def writetolistwidget(self, lis, liswid):
		liswid.clear()
		for i in lis:
			liswid.addItem(i)

	def deletecurrentbkm(self):
		ct = self.form.listWidget.currentItem().text()
		self.bkmlistfromfile.remove(ct)
		self.writetolistwidget(self.bkmlistfromfile, self.bkmli)
		self.writetolistwidget(self.bkmlistfromfile, self.form.listWidget)
		cur.execute("delete from BOOKMARKS")

	def deleteallbkm(self):
		self.form.listWidget.clear()
		self.bkmli.clear()
		self.bkmlistfromfile = []
		cur.execute("delete from BOOKMARKS")

	def viewbkmf(self):
		self.form = managebkm(self)
		self.writetolistwidget(self.bkmlistfromfile, self.form.listWidget)
		self.form.show()
		self.connect(self.form.closebtn, SIGNAL("clicked()"), self.form.close)
		self.connect(self.form.sortbtn, SIGNAL("clicked()"), self.sortit)
		self.connect(self.form.deletebtn, SIGNAL("clicked()"), self.deletecurrentbkm)
		self.connect(self.form.deleteallbtn, SIGNAL("clicked()"), self.deleteallbkm)

	def aboutf(self):
		QMessageBox.about(self, "About Nigandu English to Tamil Dictionary",
		                  """<b>Nigandu English to Tamil Dictionary</b> v %s
			                  <p>This is the first corss-platform English to Tamil
			                  bilingual dictionary; Free to use.</p>
			                  <p>Copyright &copy; 2014 NJN Private Ltd.
	                             All rights reserved.</p>
	                          <p>Thanks to Python and PySide Project.</p>
	                          <p>Using Python 3.3, Qt 4.8 and PySide 1.2.1</p>""" % (__version__))

	def visitblogf(self):
		webbrowser.open("http://www.e-nool.blogspot.com")
Ejemplo n.º 32
0
    def __init__(self, parent=None):
        ''' sets up the whole main window '''

        #standard init
        super(MainWindow, self).__init__(parent)

        #set the window title
        self.setWindowTitle('Open Ephys Control GUI')

        self.window_height = 700
        self.window_width = 1100

        self.screen2 = QDesktopWidget().screenGeometry(0)
        self.move(
            self.screen2.left() +
            (self.screen2.width() - self.window_width) / 2.,
            self.screen2.top() +
            (self.screen2.height() - self.window_height) / 2.)

        self.get_info()
        self.noinfo = True

        while self.noinfo:
            loop = QEventLoop()
            QTimer.singleShot(500., loop.quit)
            loop.exec_()

        subprocess.Popen('start %s' % open_ephys_path, shell=True)

        self.collect_frame.connect(self.update_frame)
        self.collect_threshed.connect(self.update_threshed)
        self.acquiring = False
        self.recording = False

        self.video_height = self.window_height * .52
        self.video_width = self.window_width * .48

        self.resize(self.window_width, self.window_height)

        #create QTextEdit window 'terminal' for receiving stdout and stderr
        self.terminal = QTextEdit(self)
        #set the geometry
        self.terminal.setGeometry(
            QRect(self.window_width * .02,
                  self.window_height * .15 + self.video_height,
                  self.video_width * .96, 150))

        #make widgets
        self.setup_video_frames()
        self.setup_thresh_buttons()

        self.overlay = True

        #create thread and worker for video processing
        self.videoThread = QThread(self)
        self.videoThread.start()
        self.videoproc_worker = VideoWorker(self)
        self.videoproc_worker.moveToThread(self.videoThread)

        self.vt_file = None
        """""" """""" """""" """""" """""" """""" """""" """
        set up menus
        """ """""" """""" """""" """""" """""" """""" """"""

        #create a QMenuBar and set geometry
        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(
            QRect(0, 0, self.window_width * .5, self.window_height * .03))
        #set the QMenuBar as menu bar for main window
        self.setMenuBar(self.menubar)

        #create a QStatusBar
        statusbar = QStatusBar(self)
        #set it as status bar for main window
        self.setStatusBar(statusbar)

        #create icon toolbar with default image
        iconToolBar = self.addToolBar("iconBar.png")

        #create a QAction for the acquire button
        self.action_Acq = QAction(self)
        #make it checkable
        self.action_Acq.setCheckable(True)
        #grab an icon for the button
        acq_icon = self.style().standardIcon(QStyle.SP_MediaPlay)
        #set the icon for the action
        self.action_Acq.setIcon(acq_icon)
        #when the button is pressed, call the Acquire function
        self.action_Acq.triggered.connect(self.Acquire)

        #create a QAction for the record button
        self.action_Record = QAction(self)
        #make it checkable
        self.action_Record.setCheckable(True)
        #grab an icon for the button
        record_icon = self.style().standardIcon(QStyle.SP_DialogYesButton)
        #set the icon for the action
        self.action_Record.setIcon(record_icon)
        #when the button is pressed, call advanced_settings function
        self.action_Record.triggered.connect(self.Record)

        #create QAction for stop button
        action_Stop = QAction(self)
        #grab close icon
        stop_icon = self.style().standardIcon(QStyle.SP_MediaStop)
        #set icon for action
        action_Stop.setIcon(stop_icon)
        #when button pressed, close window
        action_Stop.triggered.connect(self.Stop)

        #show tips for each action in the status bar
        self.action_Acq.setStatusTip("Start acquiring")
        self.action_Record.setStatusTip("Start recording")
        action_Stop.setStatusTip("Stop acquiring/recording")

        #add actions to icon toolbar
        iconToolBar.addAction(self.action_Acq)
        iconToolBar.addAction(self.action_Record)
        iconToolBar.addAction(action_Stop)

        #        self.sort_button = QPushButton('Sort Now',self)
        #        self.sort_button.setGeometry(QRect(self.window_width*.85,0,self.window_width*.15,self.window_height*.05))
        #        self.sort_button.clicked.connect(self.sort_now)

        #show the window if minimized by windows
        self.showMinimized()
        self.showNormal()
        """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" ""
        """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" ""
Ejemplo n.º 33
0
	def __init__(self, parent=None):
		super(mainwin, self).__init__(parent)
		self.setWindowTitle("Nigandu English to Tamil Dictionary")
		self.setGeometry(200, 50, 650, 600)
		self.setMinimumHeight(620)
		self.setMinimumWidth(650)
		self.setMaximumHeight(660)
		self.setMaximumWidth(800)
		#Setting up status bar
		self.myStatusBar = QStatusBar()
		self.myStatusBar.showMessage('Ready', 7000)
		self.setStatusBar(self.myStatusBar)
		#Setting up application icon
		appIcon = QIcon(":/icons/njnlogo.png")
		self.setWindowIcon(appIcon)

		# defining the central widget
		self.central = QWidget(self)

		#combobox plus search button
		self.whole = QVBoxLayout(self.central)
		self.gridlayout = QGridLayout()
		self.comboBox = QLineEdit(self)
		#self.comboBox.setEditable(True)
		self.comboBox.setObjectName("comboBox")
		self.completer = QCompleter(self.comboBox)
		self.completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion)
		self.completer.setCaseSensitivity(Qt.CaseInsensitive)
		self.completer.setMaxVisibleItems(10)
		self.comboBox.setCompleter(self.completer)
		#self.comboBox.setCompleter()
		self.gridlayout.addWidget(self.comboBox, 1, 1, 1, 2)

		self.searchbtn = QPushButton()
		self.searchbtn.setObjectName("searchbtn")
		self.searchbtn.setText("&Search")
		self.gridlayout.addWidget(self.searchbtn, 1, 3)

		vbox = QVBoxLayout()
		self.tamtext = QTextBrowser()
		self.listview = QListWidget(self)
		#self.listview.setEditTriggers(QAbstractItemView.NoEditTriggers)
		self.listview.setWindowTitle("Suggested words")
		self.tamtext.setMinimumHeight(100)
		self.tamtext.setMaximumHeight(150)
		vbox.addWidget(self.tamtext)
		self.suglbl = QLabel(self)
		self.suglbl.setText("Suggested Words:")
		vbox.addWidget(self.suglbl)
		vbox.addWidget(self.listview)

		self.whole.addLayout(self.gridlayout)
		self.whole.addLayout(vbox)
		self.setCentralWidget(self.central)

		#setting docks
		self.histdockwidg = QDockWidget("History", self)
		self.bkmdockwidg = QDockWidget("Book Marks", self)
		self.histdockwidg.setObjectName("self.histdockwidg")
		self.bkmdockwidg.setObjectName("self.bkmdockwidg")

		#self.histdockwidg.setMaximumWidth(histwidth)
		self.histdockwidg.setAllowedAreas(Qt.RightDockWidgetArea)
		self.bkmdockwidg.setAllowedAreas(Qt.RightDockWidgetArea)
		self.histdockwidg.setMaximumWidth(250)
		self.bkmdockwidg.setMaximumWidth(250)
		self.histdockwidg.setMinimumWidth(200)
		self.bkmdockwidg.setMinimumWidth(200)

		#self.bkmdockwidg.setMaximumWidth(histwidth)
		self.histli = QListWidget()
		self.bkmli = QListWidget()
		self.histlis = [0]
		self.bkmlistfromfile = []
		self.histdockwidg.setWidget(self.histli)
		self.bkmdockwidg.setWidget(self.bkmli)
		self.addDockWidget(Qt.RightDockWidgetArea, self.histdockwidg)
		self.addDockWidget(Qt.RightDockWidgetArea, self.bkmdockwidg)

		#file menu
		fi_addwrd = self.createactions("&Add a word...", self.addwrdf, "Alt+A", ":/icons/add.png",
		                               "Add a word to the dictionary. . .")
		fi_options = self.createactions("&Options", self.optionsf, "None", ":/icons/options.png",
		                                "Change the default settings. . .")
		fi_help = self.createactions("&Help", self.helpf, QKeySequence.HelpContents, ":/icons/help.png",
		                             "Help contents. . .")
		fi_quit = self.createactions("&Quit", self.close, QKeySequence.Close, ":/icons/quit.png",
		                             "Close the application. . .")
		fplus = self.createactions("FontPlus", self.fplusf, "None", ":/icons/fplus.png", "Increase the font size")
		fminus = self.createactions("FontMinus", self.fminusf, "None", ":/icons/fminus.png", "Decrease the font size")
		#list of file actions
		fi_menu = (fi_addwrd, fi_options, fi_help, None, fi_quit)

		#go menu
		self.go_prev = self.createactions("&Previous Word", self.prevf, "Alt+Z", ":/icons/prev.png",
		                                  "Previous Word")
		self.go_next = self.createactions("&Next Word", self.nextf, "Alt+X", ":/icons/next.png", "Next Word")
		self.go_rand = self.createactions("&Random Word", self.randf, "Ctrl+R", ":/icons/rand.png",
		                                  "Select a random word")
		#list of go actions
		go_menu = (self.go_prev, self.go_next, self.go_rand )
		self.go_next.setEnabled(False)
		self.go_prev.setEnabled(False)

		#book mark menu
		self.bkm_addfav = self.createactions("&Bookmark", self.addfavf, "Ctrl+B", ":/icons/bookmark.png",
		                                     "Book mark this word")
		self.bkm_viewbkm = self.createactions("&View Bookmarks", self.viewbkmf, "Alt+V", ":/icons/viewbkm.png",
		                                      "View bookmarked words")
		#list of book mark items
		bkm_menu = (self.bkm_addfav, self.bkm_viewbkm)

		#help menu
		hlp_about = self.createactions("Abo&ut", self.aboutf, "Ctrl+U", ":/icons/about.png", "About")
		hlp_visitblog = self.createactions("&Visit Blog", self.visitblogf, "None", ":/icons/visitblog.png",
		                                   "Visit our blog")
		hlp_help = self.createactions("&Help", self.helpf, "Ctrl+H", ":/icons/help.png", "Help Contents")
		#list of help menu items
		hlp_menu = (hlp_about, hlp_visitblog, hlp_help)

		#Setting up the menubar
		filemenu = self.menuBar().addMenu("&File")
		self.addmenu(filemenu, fi_menu)
		gomenu = self.menuBar().addMenu("&Go")
		self.addmenu(gomenu, go_menu)
		bkmmenu = self.menuBar().addMenu("&Book Mark")
		self.addmenu(bkmmenu, bkm_menu)
		helpmenu = self.menuBar().addMenu("&Help")
		self.addmenu(helpmenu, hlp_menu)
		intn = QSize(40, 40)
		self.setIconSize(intn)
		#Setting up the tool bar
		filetools = self.addToolBar("File")
		filetools.setObjectName("filetools")
		self.addmenu(filetools, (fi_addwrd, fplus, fminus))

		gotools = self.addToolBar("Go")
		gotools.setObjectName("gotools")
		self.addmenu(gotools, go_menu)

		bkmtools = self.addToolBar("Bkm")
		bkmtools.setObjectName("bkmtools")
		self.addmenu(bkmtools, bkm_menu)

		hlptools = self.addToolBar("Help")
		hlptools.setObjectName("helptools")
		self.addmenu(hlptools, hlp_menu)

		self.loadfiles()
		self.returncount = 0
		self.bkm_addfav.setEnabled(False)

		#clipboard function
		if self.clipauto:
			clip = QApplication.clipboard()
			cliptxt = clip.text()
			self.comboBox.setText(cliptxt)
			self.setevent()

		#connections
		self.connect(self.comboBox, SIGNAL("textChanged(QString)"), self.search)
		self.connect(self.comboBox, SIGNAL("returnPressed()"), self.returnpressedevent)
		self.connect(self.searchbtn, SIGNAL("clicked()"), self.onenter)
		self.connect(self.listview, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.listwidcall)
		self.connect(self.histli, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.listwidcall)
		self.connect(self.bkmli, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.listwidcall)
Ejemplo n.º 34
0
class MainWindow(QMainWindow):
    """ Our Main Window class
    """
    def __init__(self):
        """ Constructor Function
        """
        QMainWindow.__init__(self)
        self.setWindowTitle("A Simple Text Editor")
        self.setWindowIcon(QIcon('iconos/prueba.png'))
        self.setGeometry(300, 250, 400, 300)

    def SetupComponents(self):
        """ Function to setup status bar, central widget, menu bar
        """
        self.myStatusBar = QStatusBar()
        self.setStatusBar(self.myStatusBar)
        self.myStatusBar.showMessage('Ready', 10000)
        self.textEdit = QTextEdit()
        self.setCentralWidget(self.textEdit)

        self.createActions()
        self.createMenus()

        # Invoques toolbar creation and after that, reuses menu actions from
        # createActions() to create toolbar bottons.
        self.CreateToolBar()
        self.mainToolBar.addAction(self.newAction)
        self.mainToolBar.addSeparator()
        self.mainToolBar.addAction(self.copyAction)
        self.mainToolBar.addAction(self.pasteAction)

        self.fileMenu.addAction(self.newAction)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.exitAction)
        self.editMenu.addAction(self.copyAction)
        self.fileMenu.addSeparator()
        self.editMenu.addAction(self.pasteAction)
        self.helpMenu.addAction(self.aboutAction)

    # Slots called when the menu actions are triggered
    def newFile(self):
        self.textEdit.setText('')

    def exitFile(self):
        self.close()

    def aboutHelp(self):
        QMessageBox.about(self, "About Simple Text Editor",
                          "This example demonstrates the use " "of Menu Bar")

    def createActions(self):
        """ Function to create actions for menus
        """

        self.newAction = QAction(QIcon('iconos/new.png'), '&New', self,
                                 shortcut=QKeySequence.New,
                                 statusTip="Create a New File",
                                 triggered=self.newFile)
        self.exitAction = QAction(QIcon('iconos/exit.png'), 'E&xit', self,
                                  shortcut="Ctrl+Q",
                                  statusTip="Exit the Application",
                                  triggered=self.exitFile)
        self.copyAction = QAction(QIcon('iconos/copy.png'), 'C&opy', self,
                                  shortcut="Ctrl+C", statusTip="Copy",
                                  triggered=self.textEdit.copy)
        self.pasteAction = QAction(QIcon('iconos/paste.png'), '&Paste', self,
                                   shortcut="Ctrl+V", statusTip="Paste",
                                   triggered=self.textEdit.paste)
        self.aboutAction = QAction(QIcon('iconos/about.png'), 'A&bout', self,
                                   statusTip="Displays info about text editor",
                                   triggered=self.aboutHelp)

    # Actual menu bar item creation
    def createMenus(self):
        """ Function to create actual menu bar
        """
        # self.menubar() invoca una funcion nativa de la clase padre
        # QMainWindow la cual crea una barra de menu nativa al sistema de
        # ventanas en el que se ejecuta el programa, recordar el problema de
        # no buscar los menus en la barra de menus de Unity, donde estaban
        # "escondidos". El primer llamado a la funcion crea la barra y las
        # multiples invocaciones subsiguientes añaden los nuevos menus

        self.fileMenu = self.menuBar().addMenu("&File")
        self.editMenu = self.menuBar().addMenu("&Edit")
        self.helpMenu = self.menuBar().addMenu("&Help")

    def CreateToolBar(self):
        """ Function to create tool bar
        """
        self.mainToolBar = self.addToolBar('Main')
Ejemplo n.º 35
0
Archivo: gui.py Proyecto: tinavas/FSERP
    def setup(self):
        """initializes the uio of the erp client"""
        self.progress.setFixedWidth(1000)
        self.progress.setCancelButton(None)
        # self.progress.setWindowModality(Qt.WindowModal)
        self.progress.setValue(1)
        self.mainwindow.setObjectName("MainWindow")
        self.mainwindow.resize(832, 668)
        self.mainwindow.setStyleSheet(
            "QToolBar{\n"
            "background: qlineargradient(x1:0, y1:0, x2:1, y2:1,\n"
            "stop:0 rgba(0,0,0),stop:1 rgb(162, 162, 162, 162));\n"
            "border: 0px;\n"
            "}\n"
            "QToolBar > QWidget{\n"
            "color:white;\n"
            "}\n"
            "QToolBar > QWidget:hover {\n"
            "background:transparent;\n"
            " }\n"
            "QToolBar > QWidget:checked {\n"
            "background:transparent;\n"
            " }\n"
            "#MainWindow{\n"
            "background: qlineargradient(x1:0, y1:0, x2:1, y2:1,\n"
            "stop:0 rgba(0,0,0),stop:1 rgb(162, 162, 162, 162));\n"
            "border: 0px;\n"
            "}\n"
            "")
        self.centralWidget = QWidget(self.mainwindow)
        self.centralWidget.setObjectName("centralWidget")
        self.gridLayout_2 = QGridLayout(self.centralWidget)
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.stackedWidget = QStackedWidget(self.centralWidget)
        self.stackedWidget.setStyleSheet("")
        self.stackedWidget.setObjectName("stackedWidget")
        self.shortcut = NewShortcut()
        scroll = QScrollArea()
        scroll.setWidget(self.shortcut.shortcut_setting)
        self.stackedWidget.addWidget(self.shortcut.shortcut_setting)
        self.home_page = QWidget()
        self.home_page.setObjectName("home_page")
        self.gridLayout = QGridLayout(self.home_page)
        self.gridLayout.setObjectName("gridLayout")
        self.billing_frame_2 = QFrame(self.home_page)
        self.billing_frame_2.setStyleSheet(
            "background-image:url(:/images/billing_frame.png);\n"
            "background-repeat: no-repeat;\n"
            "background-position: center;\n"
            "background-color:#6CBED2;")
        self.billing_frame_2.setFrameShape(QFrame.StyledPanel)
        self.billing_frame_2.setFrameShadow(QFrame.Raised)
        self.billing_frame_2.setObjectName("billing_frame_2")
        self.verticalLayout_4 = QVBoxLayout(self.billing_frame_2)
        self.verticalLayout_4.setObjectName("verticalLayout_4")
        spacerItem = QSpacerItem(20, 217, QSizePolicy.Minimum,
                                 QSizePolicy.Expanding)
        self.verticalLayout_4.addItem(spacerItem)
        self.label_10 = QLabel(self.billing_frame_2)
        self.label_10.setStyleSheet("background:transparent;")
        self.label_10.setObjectName("label_10")
        self.verticalLayout_4.addWidget(self.label_10)
        self.gridLayout.addWidget(self.billing_frame_2, 0, 1, 1, 1)
        self.employee_frame_3 = QFrame(self.home_page)
        self.employee_frame_3.setStyleSheet(
            "background-image:url(:/images/employee_frame.png);\n"
            "background-repeat: no-repeat;\n"
            "background-position: center;\n"
            "background-color:#0099CC;")
        self.employee_frame_3.setFrameShape(QFrame.StyledPanel)
        self.employee_frame_3.setFrameShadow(QFrame.Raised)
        self.employee_frame_3.setObjectName("employee_frame_3")
        self.verticalLayout_5 = QVBoxLayout(self.employee_frame_3)
        self.verticalLayout_5.setObjectName("verticalLayout_5")
        spacerItem1 = QSpacerItem(20, 217, QSizePolicy.Minimum,
                                  QSizePolicy.Expanding)
        self.verticalLayout_5.addItem(spacerItem1)
        self.label_11 = QLabel(self.employee_frame_3)
        self.label_11.setStyleSheet("background:transparent;")
        self.label_11.setObjectName("label_11")
        self.verticalLayout_5.addWidget(self.label_11)
        self.gridLayout.addWidget(self.employee_frame_3, 0, 2, 1, 1)
        self.menu_frame_4 = QFrame(self.home_page)
        self.menu_frame_4.setStyleSheet(
            "background-image:url(:/images/menu_frame.png);\n"
            "background-repeat: no-repeat;\n"
            "background-position: center;\n"
            "background-color:#297ACC;")
        self.menu_frame_4.setFrameShape(QFrame.StyledPanel)
        self.menu_frame_4.setFrameShadow(QFrame.Raised)
        self.menu_frame_4.setObjectName("menu_frame_4")
        self.verticalLayout_3 = QVBoxLayout(self.menu_frame_4)
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        spacerItem2 = QSpacerItem(20, 216, QSizePolicy.Minimum,
                                  QSizePolicy.Expanding)
        self.verticalLayout_3.addItem(spacerItem2)
        self.label_12 = QLabel(self.menu_frame_4)
        self.label_12.setStyleSheet("background:transparent;")
        self.label_12.setObjectName("label_12")
        self.verticalLayout_3.addWidget(self.label_12)
        self.gridLayout.addWidget(self.menu_frame_4, 1, 0, 1, 1)
        self.report_frame_5 = QFrame(self.home_page)
        self.report_frame_5.setStyleSheet(
            "background-image:url(:/images/report_frame.png);\n"
            "background-repeat: no-repeat;\n"
            "background-position: center;\n"
            "background-color:#006BB2;")
        self.report_frame_5.setFrameShape(QFrame.StyledPanel)
        self.report_frame_5.setFrameShadow(QFrame.Raised)
        self.report_frame_5.setObjectName("report_frame_5")
        self.verticalLayout_6 = QVBoxLayout(self.report_frame_5)
        self.verticalLayout_6.setObjectName("verticalLayout_6")
        spacerItem3 = QSpacerItem(20, 216, QSizePolicy.Minimum,
                                  QSizePolicy.Expanding)
        self.verticalLayout_6.addItem(spacerItem3)
        self.label_13 = QLabel(self.report_frame_5)
        self.label_13.setStyleSheet("background:transparent;")
        self.label_13.setObjectName("label_13")
        self.verticalLayout_6.addWidget(self.label_13)
        self.gridLayout.addWidget(self.report_frame_5, 1, 1, 1, 1)
        self.waste_frame_6 = QFrame(self.home_page)
        self.waste_frame_6.setStyleSheet(
            "background-image:url(:/images/waste_frame.png);\n"
            "background-repeat: no-repeat;\n"
            "background-position: center;\n"
            "background-color:#003D7A;")
        self.waste_frame_6.setFrameShape(QFrame.StyledPanel)
        self.waste_frame_6.setFrameShadow(QFrame.Raised)
        self.waste_frame_6.setObjectName("waste_frame_6")
        self.verticalLayout_7 = QVBoxLayout(self.waste_frame_6)
        self.verticalLayout_7.setObjectName("verticalLayout_7")
        spacerItem4 = QSpacerItem(20, 216, QSizePolicy.Minimum,
                                  QSizePolicy.Expanding)
        self.verticalLayout_7.addItem(spacerItem4)
        self.label_14 = QLabel(self.waste_frame_6)
        self.label_14.setStyleSheet("background:transparent;")
        self.label_14.setObjectName("label_14")
        self.verticalLayout_7.addWidget(self.label_14)
        self.gridLayout.addWidget(self.waste_frame_6, 1, 2, 1, 1)
        self.inventory_frame_1 = QFrame(self.home_page)
        self.inventory_frame_1.setStyleSheet(
            "background-image:url(:/images/inventory_frame.png);\n"
            "background-repeat: no-repeat;\n"
            "background-position: center;\n"
            "background-color:#ADEBFF;")
        self.inventory_frame_1.setFrameShape(QFrame.StyledPanel)
        self.inventory_frame_1.setFrameShadow(QFrame.Raised)
        self.inventory_frame_1.setObjectName("inventory_frame_1")
        self.verticalLayout_2 = QVBoxLayout(self.inventory_frame_1)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        spacerItem5 = QSpacerItem(20, 217, QSizePolicy.Minimum,
                                  QSizePolicy.Expanding)
        self.verticalLayout_2.addItem(spacerItem5)
        self.label_9 = QLabel(self.inventory_frame_1)
        self.label_9.setStyleSheet("background:transparent;")
        self.label_9.setObjectName("label_9")
        self.verticalLayout_2.addWidget(self.label_9)
        self.gridLayout.addWidget(self.inventory_frame_1, 0, 0, 1, 1)
        self.stackedWidget.addWidget(self.home_page)
        self.detail_page = QWidget()
        self.detail_page.setObjectName("detail_page")
        self.horizontalLayout_2 = QHBoxLayout(self.detail_page)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.main_tabWidget = QTabWidget(self.detail_page)
        self.main_tabWidget.setAutoFillBackground(False)
        self.main_tabWidget.setStyleSheet("")
        self.main_tabWidget.setTabPosition(QTabWidget.West)
        self.main_tabWidget.setIconSize(QSize(60, 60))
        self.main_tabWidget.setElideMode(Qt.ElideNone)
        self.main_tabWidget.setObjectName("main_tabWidget")
        ##initializes the tabs
        self.add_tabs()
        self.main_tabWidget.setFocusPolicy(Qt.StrongFocus)
        self.main_tabWidget.focusInEvent = self.change_focus
        self.main_tabWidget.currentChanged.connect(self.change_focus)
        self.stackedWidget.currentChanged.connect(self.change_focus)
        ######
        self.horizontalLayout_2.addWidget(self.main_tabWidget)
        self.stackedWidget.addWidget(self.detail_page)
        if ('Admin', True) in self.access:
            self.stackedWidget.addWidget(Admin(self.mainwindow))
        notification = NotificationTab()
        tab = notification.notificationTab_tab_4
        tab.custom_class_object = notification  # class_object is used to access the api through the
        self.stackedWidget.addWidget(tab)
        self.gridLayout_2.addWidget(self.stackedWidget, 0, 0, 1, 1)
        self.mainwindow.setCentralWidget(self.centralWidget)
        self.menuBar = QMenuBar(self.mainwindow)
        self.menuBar.setGeometry(QRect(0, 0, 832, 29))
        self.menuBar.setObjectName("menuBar")
        self.mainwindow.setMenuBar(self.menuBar)
        self.mainToolBar = QToolBar(self.mainwindow)
        self.mainToolBar.setLayoutDirection(Qt.RightToLeft)
        self.mainToolBar.setStyleSheet("")
        self.mainToolBar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        self.mainToolBar.setObjectName("mainToolBar")
        self.mainwindow.addToolBar(Qt.TopToolBarArea, self.mainToolBar)
        self.statusBar = QStatusBar(self.mainwindow)
        self.statusBar.setObjectName("statusBar")
        self.mainwindow.setStatusBar(self.statusBar)
        self.toolBar = QToolBar(self.mainwindow)
        self.toolBar.setLayoutDirection(Qt.RightToLeft)
        self.toolBar.setStyleSheet("")
        self.toolBar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        self.toolBar.setObjectName("toolBar")
        self.mainwindow.addToolBar(Qt.TopToolBarArea, self.toolBar)
        self.actionNotification = QAction(self.mainwindow)
        self.actionNotification.setCheckable(True)
        self.actionNotification.setChecked(False)
        self.actionNotification.setEnabled(True)
        icon6 = QIcon()
        icon6.addPixmap(QPixmap(":/images/notification.png"), QIcon.Normal,
                        QIcon.Off)
        self.actionNotification.setIcon(icon6)
        self.actionNotification.setAutoRepeat(True)
        self.actionNotification.setVisible(True)
        self.actionNotification.setIconVisibleInMenu(False)
        self.actionNotification.setObjectName("actionNotification")
        self.actionNotification
        self.actionAdmin = QAction(self.mainwindow)
        # self.actionAdmin.setCheckable(True)
        icon7 = QIcon()
        icon7.addPixmap(QPixmap(":/images/admin.png"), QIcon.Normal, QIcon.Off)
        self.actionAdmin.setIcon(icon7)
        self.actionAdmin.setObjectName("actionAdmin")
        self.actionRefresh = QAction(self.mainwindow)
        icon8 = QIcon()
        icon8.addPixmap(QPixmap(":/images/refresh.png"), QIcon.Normal,
                        QIcon.Off)
        self.actionRefresh.setIcon(icon8)
        self.actionRefresh.setObjectName("actionRefresh")
        self.actionHome = QAction(self.mainwindow)
        # self.actionHome.setCheckable(True)
        icon9 = QIcon()
        icon9.addPixmap(QPixmap(":/images/home.png"), QIcon.Normal, QIcon.Off)
        self.actionHome.setIcon(icon9)
        self.actionHome.setObjectName("actionHome")
        self.actionSettings = QAction(self.mainwindow)
        icon10 = QIcon()
        icon10.addPixmap(QPixmap(":/images/settings.png"), QIcon.Normal,
                         QIcon.Off)
        self.actionSettings.setIcon(icon10)
        self.actionSettings.setObjectName("actionRefresh")
        self.toolBar.addAction(self.actionNotification)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.actionAdmin)
        if ('Admin', True) in self.access:
            self.toolBar.addSeparator()
        else:
            self.actionAdmin.setVisible(False)
        self.toolBar.addAction(self.actionHome)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.actionRefresh)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.actionSettings)
        ##retranslates
        self.mainwindow.setWindowTitle(
            QApplication.translate("MainWindow", settings.company, None,
                                   QApplication.UnicodeUTF8))
        self.label_10.setText(
            QApplication.translate(
                "MainWindow",
                "<html><head/><body><p align=\"center\">BILLING</p></body></html>",
                None, QApplication.UnicodeUTF8))
        self.label_11.setText(
            QApplication.translate(
                "MainWindow",
                "<html><head/><body><p align=\"center\">EMPLOYEE</p></body></html>",
                None, QApplication.UnicodeUTF8))
        self.label_12.setText(
            QApplication.translate(
                "MainWindow",
                "<html><head/><body><p align=\"center\">MENU</p></body></html>",
                None, QApplication.UnicodeUTF8))
        self.label_13.setText(
            QApplication.translate(
                "MainWindow",
                "<html><head/><body><p align=\"center\">REPORT</p></body></html>",
                None, QApplication.UnicodeUTF8))
        self.label_14.setText(
            QApplication.translate(
                "MainWindow",
                "<html><head/><body><p align=\"center\">WASTE</p></body></html>",
                None, QApplication.UnicodeUTF8))
        self.label_9.setText(
            QApplication.translate(
                "MainWindow",
                "<html><head/><body><p align=\"center\">INVENTORY</p></body></html>",
                None, QApplication.UnicodeUTF8))
        self.inventory_frame_1.setToolTip(
            QApplication.translate("MainWindow", "Go to the Inventory Tab",
                                   None, QApplication.UnicodeUTF8))
        self.billing_frame_2.setToolTip(
            QApplication.translate("MainWindow", "Go to the Billing Tab", None,
                                   QApplication.UnicodeUTF8))
        self.employee_frame_3.setToolTip(
            QApplication.translate("MainWindow", "Go to the Employee Tab",
                                   None, QApplication.UnicodeUTF8))
        self.menu_frame_4.setToolTip(
            QApplication.translate("MainWindow", "Go to the Menu Tab", None,
                                   QApplication.UnicodeUTF8))
        self.report_frame_5.setToolTip(
            QApplication.translate("MainWindow", "Go to the Report Tab", None,
                                   QApplication.UnicodeUTF8))
        self.waste_frame_6.setToolTip(
            QApplication.translate("MainWindow", "Go to the Waste Tab", None,
                                   QApplication.UnicodeUTF8))
        self.toolBar.setWindowTitle(
            QApplication.translate("MainWindow", "toolBar", None,
                                   QApplication.UnicodeUTF8))
        self.actionNotification.setText("&&Notification")
        # QApplication.translate("MainWindow", "&Notification", None, QApplication.UnicodeUTF8))
        self.actionNotification.setToolTip(
            QApplication.translate("MainWindow",
                                   "Click to see new notifications", None,
                                   QApplication.UnicodeUTF8))
        # self.actionNotification.setShortcut(
        # QApplication.translate("MainWindow", "Ctrl+Shift+N", None, QApplication.UnicodeUTF8))
        self.actionAdmin.setText('&&Admin')
        # QApplication.translate("MainWindow", "Admin", None, QApplication.UnicodeUTF8))
        self.actionAdmin.setToolTip(
            QApplication.translate("MainWindow",
                                   "Click to go to admin interface", None,
                                   QApplication.UnicodeUTF8))
        # self.actionAdmin.setShortcut(
        # QApplication.translate("MainWindow", "Ctrl+Shift+A", None, QApplication.UnicodeUTF8))
        self.actionRefresh.setText("&&Refresh")
        # QApplication.translate("MainWindow", "Refresh", None, QApplication.UnicodeUTF8))
        self.actionRefresh.setToolTip(
            QApplication.translate("MainWindow",
                                   "refreshes the data from the server", None,
                                   QApplication.UnicodeUTF8))
        # self.actionRefresh.setShortcut(
        # QApplication.translate("MainWindow", "Ctrl+Shift+R", None, QApplication.UnicodeUTF8))
        self.actionHome.setText('&&Home')
        # QApplication.translate("MainWindow", "Home", None, QApplication.UnicodeUTF8))
        self.actionHome.setToolTip(
            QApplication.translate("MainWindow", "Go back to the home screen",
                                   None, QApplication.UnicodeUTF8))
        self.actionSettings.setText('&&Settings')
        # QApplication.translate("MainWindow", "Settings", None, QApplication.UnicodeUTF8))
        self.actionSettings.setToolTip(
            QApplication.translate("MainWindow", "Go to the settings panel",
                                   None, QApplication.UnicodeUTF8))
        # self.actionHome.setShortcut(
        #     QApplication.translate("MainWindow", "Ctrl+Shift+H", None, QApplication.UnicodeUTF8))
        self.stackedWidget.setCurrentIndex(1)
        self.main_tabWidget.setCurrentIndex(0)

        self.ob = self.main_tabWidget.tabBar()
        # self.add_tool_tip(self.ob) todo avoided due to segmentation fault error, left for future fixes
        self.tb = EventHandlerForTabBar()
        self.ob.installEventFilter(self.tb)

        QMetaObject.connectSlotsByName(self.mainwindow)
Ejemplo n.º 36
0
    def __init__(self):
        # ====================
        # Constructor Function
        # ====================

        QMainWindow.__init__(self)
        self.setWindowTitle("Virtua Text Editor")
        self.setGeometry(300, 300, 1024, 768)

        QToolTip.setFont(QFont("Ubuntu", 10, QFont.Normal))
        self.setToolTip('Application Window')

        # ================================
        # Function to setup menus, etc etc
        # ================================
        self.textEdit = QTextEdit()
        self.textEdit.setFont(QFont("Ubuntu", 12, QFont.Normal))
        self.setCentralWidget(self.textEdit)
        self.create_menus()
        self.create_actions()

        self.fileMenu.addAction(self.newAction)
        self.fileMenu.addAction(self.openAction)
        self.fileMenu.addAction(self.saveAction)
        self.fileMenu.addAction(self.saveasAction)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.printAction)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.exitAction)

        self.editMenu.addAction(self.undoAction)
        self.editMenu.addAction(self.redoAction)
        self.editMenu.addAction(self.cutAction)
        self.editMenu.addAction(self.copyAction)
        self.editMenu.addAction(self.pasteAction)
        self.editMenu.addSeparator()
        self.editMenu.addAction(self.selectallAction)
        self.editMenu.addAction(self.deselectallAction)
        self.editMenu.addSeparator()
        self.editMenu.addAction(self.findAction)
        self.editMenu.addAction(self.findReplaceAction)

        self.helpMenu.addAction(self.aboutAction)

        self.app_status_bar = QStatusBar()
        self.app_status_bar.showMessage('Ready, v0.2', 10000)
        self.setStatusBar(self.app_status_bar)

        self.create_toolbar()
        self.toolbar.addAction(self.newAction)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.cutAction)
        self.toolbar.addAction(self.copyAction)
        self.toolbar.addAction(self.pasteAction)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.printAction)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.undoAction)
        self.toolbar.addAction(self.redoAction)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.findAction)
        self.toolbar.addAction(self.findReplaceAction)
Ejemplo n.º 37
0
class MyMDIApp(QMainWindow):
    def __init__(self):
        super(MyMDIApp, self).__init__()

        self.setGeometry(50, 40, 1200, 960)
        # self.setAcceptDrops(True)

        self.filelist = []

        # ====================================
        # UIの生成
        # ====================================
        # :: MDIワークスペースのインスタンス化
        self.workspace = QWorkspace()
        self.workspace.setWindowTitle("Simple WorkSpace Exmaple")

        # :: lite_listview
        self.lite_listview = LiteListView()
        self.lite_listview.addItems(["abc", "def", "ghi", "jkl"])
        self.lite_listview.resize(150, 300)
        self.workspace.addWindow(self.lite_listview)

        # :: ボタンs
        layout = QHBoxLayout()
        self.btn_ana = QPushButton("Analysis")
        self.btn_plot = QPushButton("Plot")
        self.btn_save = QPushButton("Save")
        layout.addWidget(self.btn_ana)
        layout.addWidget(self.btn_plot)
        layout.addWidget(self.btn_save)
        self.btn_wid = QWidget()
        self.btn_wid.setWindowTitle("Feauters Analysis")
        self.btn_wid.setLayout(layout)
        self.workspace.addWindow(self.btn_wid)

        # :: Figure.FigureImapctAndHarmonic
        # : FIH用FigureCanvasグラフオブジェクト
        self.fig_impandharm = FigureImapctAndHarmonic()
        self.fig_impandharm.setWindowTitle("Figure Impact & Harmonic")
        self.workspace.addWindow(self.fig_impandharm)
        self.fig_impandharm.close()

        # : 以下コントローラ
        layout2 = QHBoxLayout()
        self.fih_label = QLabel()
        self.fih_label.setText(self.tr("Impact & Harm"))
        self.fih_btn_ana = QPushButton("Analysis")
        self.fih_btn_plot = QPushButton("Plot")
        self.fih_btn_save = QPushButton("Save")
        layout2.addWidget(self.fih_label)
        layout2.addWidget(self.fih_btn_ana)
        layout2.addWidget(self.fih_btn_plot)
        layout2.addWidget(self.fih_btn_save)
        self.btn_wid2 = QWidget()
        self.btn_wid2.setWindowTitle("Imapct & Harm")
        self.btn_wid2.setLayout(layout2)
        self.workspace.addWindow(self.btn_wid2)

        self.fih_btn_ana.clicked.connect(self.run_FIH_analysis)
        self.fih_btn_plot.clicked.connect(self.run_FIH_plot)
        self.fih_btn_save.clicked.connect(self.fig_impandharm.save)


        # :: キャンバス
        self.sig_canvas = SignalDataCanvas()
        # self.sig_canvas.setWindowTitle(self.tr(u"特徴量グラフ"))
        self.sig_canvas.setWindowTitle(u"特徴量グラフ")
        self.workspace.addWindow(self.sig_canvas)
        self.sig_canvas.close()

        # :: ステータスバー
        self.myStatusBar = QStatusBar()
        self.setStatusBar(self.myStatusBar)
        self.myStatusBar.showMessage('Ready', 1000)
        # :: プログラスバー
        self.progressBar = QProgressBar()
        self.myStatusBar.addPermanentWidget(self.progressBar)
        self.progressBar.reset()
        self.progressBar.setVisible(False)
        self.progressBar.setValue(0)

        # :: MainWidgetに追加
        # self.workspace.tile()
        self.setCentralWidget(self.workspace)
        self.setCSS()

        # ====================================
        # シグナルスロットのコネクト
        # ====================================
        # lite_listview
        self.lite_listview.fileDropped.connect(self.set_filelist)
        self.lite_listview.clicked.connect(self.file_selected)
        # Analysisボタンで解析実行
        self.btn_ana.clicked.connect(self.run_analysis)
        self.btn_plot.clicked.connect(self.run_plot)

    # *****************************************************
    # ファイルインプット用スロット
    # *****************************************************
    @Slot()
    def file_selected(self, index):
        """listviewがクリックされたときの動作"""
        selected_stritem = index.data(Qt.DisplayRole)
        s = "Clicked[%d] : %r" % (index.row(), selected_stritem)
        self.flush(s)

    @Slot()
    def set_filelist(self, file_list):
        self.filelist = file_list
        self.flush("Load File List")

    # *****************************************************
    # Window2: インパクト音&自由振動音解析用
    # *****************************************************
    @Slot()
    def run_FIH_analysis(self):
        """解析データの受け渡し用中間スロット"""
        self.flush("> (QThread) run analysis")
        self.p2 = thread_analysis_imp_and_hrm()
        self.p2.set_option(self.filelist)
        self.p2.progress.connect(self.progress)
        self.p2.start()

    @Slot()
    def run_FIH_plot(self):
        res = self.p2.get_result()
        self.fig_impandharm.plot(resuls=res)
        pass

    # *****************************************************
    # Window1: 全データ統計解析用
    # *****************************************************
    @Slot()
    def run_analysis(self):
        """特徴量算出アルゴリズム実行"""
        self.flush("> (QThread) run analysis")
        self.p = thProcess()
        self.p.set_option(self.filelist)
        self.p.progress.connect(self.progress)
        self.p.start()

    @Slot()
    def run_plot(self):
        """特徴量マップの表示"""
        # ; データ取得
        # res = array(self.result)
        res = array(self.p.get_result())
        # :
        canvas = BubleChartCanvas()
        self.workspace.addWindow(canvas)
        canvas.show()
        # グラフプロット
        names = [os.path.basename(p) for p in self.filelist]
        canvas.bubbleplot(xdata=res[:, 0], data=res[:, 1], names=names)
        canvas.set_xlabel("Katasa").set_ylabel("Matomari").canvas_update()

    # *****************************************************
    # 共通関数
    # *****************************************************
    def flush(self, s, ms=1):
        maxlen = 50
        if len(s) > maxlen:
            s = s[:10] + "..." + s[-maxlen:]
        self.myStatusBar.showMessage(s, ms * 1000)

    def progress(self, value=None):
        if value < 0:
            self.progressBar.reset()
            self.progressBar.setVisible(False)
        if value >= 0:
            self.progressBar.setVisible(True)
            self.progressBar.setValue(value)

    def setCSS(self):
        """cssを読みこんでセット        """
        with open(CSS_PATH, "r") as f:
            self.setStyleSheet("".join(f.readlines()))