Ejemplo n.º 1
0
	def keyReleaseEvent_(self, ev):
		if ev.key() == Qt.Key_PageUp:
			self.imageviewer.prevImage_s()
		elif ev.key() == Qt.Key_PageDown:
			self.imageviewer.nextImage_s()
		else:
			QScrollArea.keyReleaseEvent(self, ev)
Ejemplo n.º 2
0
 def createDialogCenterWidget(self, formation):
   '''
   Scrolling list of editor widgets for editing StyleProperty.
   List comprises labels, and labeled editing widgets.
   But labels are indented as a tree.
   
   Canonical way: nest widget, layout, scrollarea
   '''
   formationLayout = formation.getLayout(top=True)
   viewport = QWidget()
   viewport.setLayout(formationLayout)
   
   # A hack so scroll bars not obscure buttons?
   # !!! left, top, right, bottom (not top, left... as usual.)
   viewport.setContentsMargins(10, 10, 10, 10)
   
   scrollArea = QScrollArea()
   scrollArea.setWidget(viewport)
   
   '''
   Assert width of contents is less than screen width (even mobile screens.)
   Can't assert height of contents less than screen height,
   e.g. a stylesheet has large height that must be vertically scrolled.
   Note this is statically determined, at design time,
   by ensuring that all rows are narrow.
   TODO dynamically enable horizontal and vertical scroll bar policy
   by calculations based on screen size and size of dialog needs?
   
   At one time, this not work: it obscured contents.
   Before I shortened many labels and model names???
   '''
   scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
   return scrollArea
    def initView(self):
        '''创建界面'''
        scrollArea = QScrollArea(self)    # 滚动区域
        scrollArea.setWidgetResizable(True)
        self.setCentralWidget(scrollArea)

        scrollWidget = QWidget()
        scrollArea.setWidget(scrollWidget)
        gridLayout = QGridLayout(scrollWidget)    # 网格布局

        # 从QEasingCurve获取所有的type
        curve_types = [(n, c) for n, c in QEasingCurve.__dict__.items()
            if isinstance(c, QEasingCurve.Type)]
        curve_types.sort(key = lambda ct: ct[1])
        i = 0
        for curve_name, curve_type in curve_types:
            index = curve_type % 4
            widget = QWidget()
            widget.setObjectName("_BorderWidget")
            widget.setStyleSheet("QWidget#_BorderWidget{border: 1px solid black;}")
            name = QLabel("QEasingCurve." + curve_name, widget)
            mpb = MetroProgressCircleBar(widget, curve_type)
            layout = QVBoxLayout(widget)
            layout.addWidget(name)
            layout.addWidget(mpb)
            gridLayout.addWidget(widget, i, index, 1, 1)
            if index == 3:
                i += 1
Ejemplo n.º 4
0
    def __init__(self, signalNames):
        super(MainWindow, self).__init__()

        widget = QWidget()
        self.setCentralWidget(widget)

        self.consoleView = ConsoleView()
        self.signalView = SignalView()
        buttonsWidget = QWidget()

        scroll = QScrollArea()
        scroll.setWidget(self.signalView)
        scroll.setWidgetResizable(True)

        hboxSignalButtons = QHBoxLayout()
        self.signalButtons = self.createSignalButtons(signalNames,
                                                      hboxSignalButtons)
        buttonsWidget.setLayout(hboxSignalButtons)

        splitter = QSplitter(self)
        splitter.setOrientation(Qt.Vertical)
        splitter.addWidget(scroll)
        splitter.addWidget(self.consoleView)
        vbox = QVBoxLayout()
        vbox.addWidget(buttonsWidget)
        vbox.addWidget(splitter)
        

        self.createActions()
        self.createMenu()

        widget.setLayout(vbox)
        self.setWindowTitle("kit")
Ejemplo n.º 5
0
    def update(self):
        for _ in range(self.layout().count()):
            self.layout().itemAt(0).widget().close()
            self.layout().takeAt(0)

        qsa = QScrollArea()
        scroll_area_widget = QWidget()
        layout = QVBoxLayout()
        scroll_area_widget.setLayout(layout)

        model = self.result.model
        cycles_per_ms = model.cycles_per_ms
        for proc in model.processors:
            proc_r = self.result.processors[proc]
            gb = QGroupBox(proc.name)
            gb_layout = QVBoxLayout()
            gb.setLayout(gb_layout)
            gb_layout.addWidget(QLabel(
                "Cxt Save count: {}".format(proc_r.context_save_count)))
            gb_layout.addWidget(QLabel(
                "Cxt Load count: {}".format(proc_r.context_load_count)))
            gb_layout.addWidget(QLabel(
                "Cxt Save overhead: {0:.4f}ms ({1:.0f} cycles)".format(
                    float(proc_r.context_save_overhead) / cycles_per_ms,
                    proc_r.context_save_overhead)))
            gb_layout.addWidget(QLabel(
                "Cxt Load overhead: {0:.4f}ms ({1:.0f} cycles)".format(
                    float(proc_r.context_load_overhead) / cycles_per_ms,
                    proc_r.context_load_overhead)))

            layout.addWidget(gb)

        qsa.setWidget(scroll_area_widget)
        self.layout().addWidget(qsa)
Ejemplo n.º 6
0
 def _create_translators_tab(self):
     translators = [
         (_('Catalan'), [u'Jaume Barcelo']),
         (_('German'), []),
         (_('Galician'), [u'Jesús Arias Fisteus']),
         (_('French'), []),
         (_('Portuguese'), []),
         (_('Spanish'), [u'Jesús Arias Fisteus']),
         ]
     parts = []
     for language, names in sorted(translators,
                                   key=DialogAbout._tuple_strxfrm):
         if names:
             parts.append(u'<p><b>{0}:</b></p>'.format(language))
             parts.append(u'<ul>')
             for name in names:
                 parts.append(u'<li>{0}</li>'.format(name))
             parts.append(u'</ul>')
     label = QLabel(u''.join(parts))
     label.setTextInteractionFlags((Qt.LinksAccessibleByKeyboard
                                    | Qt.LinksAccessibleByMouse
                                    | Qt.TextBrowserInteraction
                                    | Qt.TextSelectableByKeyboard
                                    | Qt.TextSelectableByMouse))
     scroll_area = QScrollArea(self.parent())
     scroll_area.setWidget(label)
     return scroll_area
Ejemplo n.º 7
0
    def widgetImage(self):
        """Create main image display.
        """
        imageArea = QHBoxLayout()
        scroll = QScrollArea()
        scroll.setAlignment(QtCore.Qt.AlignCenter)
        self.imageLabel = QLabel(self)

        scroll.setWidget(self.imageLabel)
        next = QPushButton(self.tr('>'))
        next.clicked.connect(self.nextCluster)
        prev = QPushButton(self.tr('<'))
        prev.clicked.connect(self.prevCluster)
        imageArea.addWidget(prev)
        imageArea.addWidget(scroll)
        imageArea.addWidget(next)

        vbox = QVBoxLayout()
        self.clusterCountLabel = QLabel(self)
        self.clusterCountLabel.setAlignment(QtCore.Qt.AlignCenter)
        f = QtGui.QFont('Arial', 14, QtGui.QFont.Bold);
        self.clusterCountLabel.setFont(f)
        vbox.addWidget(self.clusterCountLabel)
        vbox.addLayout(imageArea)
        return vbox
Ejemplo n.º 8
0
    def __init__(self, parent=None):
        super(SourceWidget, self).__init__(parent)

        self.mimeData = None

        imageFile = QFile(':/images/example.svg')
        imageFile.open(QIODevice.ReadOnly)
        self.imageData = imageFile.readAll()
        imageFile.close()

        imageArea = QScrollArea()
        self.imageLabel = QSvgWidget()
        self.imageLabel.renderer().load(self.imageData)
        imageArea.setWidget(self.imageLabel)

        instructTopLabel = QLabel("This is an SVG drawing:")
        instructBottomLabel = QLabel("Drag the icon to copy the drawing as a PNG file:")
        dragIcon = QPushButton("Export")
        dragIcon.setIcon(QIcon(':/images/drag.png'))
        dragIcon.pressed.connect(self.startDrag)

        layout = QGridLayout()
        layout.addWidget(instructTopLabel, 0, 0, 1, 2)
        layout.addWidget(imageArea, 1, 0, 2, 2)
        layout.addWidget(instructBottomLabel, 3, 0)
        layout.addWidget(dragIcon, 3, 1)
        self.setLayout(layout)
        self.setWindowTitle("Delayed Encoding")
    def initUI(self, complete, back):
        self.completeButtonClick = complete
        self.backButtonClick = back

        main_layout = QHBoxLayout()

        self.photo_load_button = QPushButton("Load photo")
        self.complete_button = QPushButton("Complete")
        self.back_button = QPushButton("Back")

        self.photo_load_button.clicked.connect(self.loadPhotoDialog)

        if self.completeButtonClick is not None:
            self.complete_button.clicked.connect(self.nextState)
        if self.backButtonClick is not None:
            self.back_button.clicked.connect(self.backButtonClick)

        toolbar = QToolbar()
        toolbar.addWidgetToToolbar(self.photo_load_button)
        toolbar.addWidgetToToolbar(self.complete_button)
        toolbar.addWidgetToToolbar(self.back_button)
        toolbar.addStretch(1)

        self.viewer = QViewer()
        viewer_scroll = QScrollArea()
        viewer_scroll.setWidget(self.viewer)
        viewer_scroll.setWidgetResizable(True)

        main_layout.addWidget(toolbar)
        main_layout.addWidget(viewer_scroll)
        main_layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(main_layout)
Ejemplo n.º 10
0
	def createWidgets(self):
		"""Cette fonction permet la création de tous les widgets de la
		mainWindow"""
		
		#Création toolbar
		toolBar = self.addToolBar("Tools")
		
		#Création bar recherche
		self.lineEditSearch = QLineEdit()
		self.lineEditSearch.setPlaceholderText("Recherche")
		self.lineEditSearch.setStyleSheet("background-color:white")
		toolBar.addWidget(self.lineEditSearch)
		self.lineEditSearch.setMaximumWidth(300)
		
		#Création séparateur
		toolBar.addSeparator()
		
		#Création icon add contact
		self.actionAdd = QAction("Ajouter (Ctrl+P)",self)
		toolBar.addAction(self.actionAdd)
		self.actionAdd.setShortcut("Ctrl+P")
		self.actionAdd.setIcon(QIcon("Pictures/sign.png"))
		
		#Création icon delete contact
		self.actionDelete = QAction("supprimer (Ctrl+D)",self)
		toolBar.addAction(self.actionDelete)	
		self.actionDelete.setShortcut("Ctrl+D")
		self.actionDelete.setIcon(QIcon("Pictures/contacts.png"))
		
		#Création icon quit
		self.actionQuitter = QAction("Quitter (Ctrl+Q)",self)
		toolBar.addAction(self.actionQuitter)
		self.actionQuitter.setShortcut("Ctrl+Q")
		self.actionQuitter.setIcon(QIcon("Pictures/arrows.png"))
		
		#Création widget central
		self.centralWidget = QWidget()
		self.centralWidget.setStyleSheet("background-color:white")
		self.setCentralWidget(self.centralWidget)
		
		
		#Création dockWidget left
		dockDisplay = QDockWidget("Répertoire")
		dockDisplay.setStyleSheet("background-color:white")
		dockDisplay.setFeatures(QDockWidget.DockWidgetFloatable)
		dockDisplay.setAllowedAreas(Qt.LeftDockWidgetArea | 
			Qt.RightDockWidgetArea)
		self.addDockWidget(Qt.LeftDockWidgetArea,dockDisplay)
		containDock = QWidget(dockDisplay)
		dockDisplay.setWidget(containDock)
		dockLayout = QVBoxLayout()
		displayWidget = QScrollArea()
		displayWidget.setWidgetResizable(1)
		dockLayout.addWidget(displayWidget)
		containDock.setLayout(dockLayout)
		
		#Ajouter la list au dockwidget
		self.listContact = QListWidget()
		displayWidget.setWidget(self.listContact)
    def __init__(self, parent = None, direction = "ltr", rtf = False):
        """ Creates a new QPageWidget on given parent object. 

        parent: QWidget parent
        direction: "ltr" -> Left To Right
                   "ttb" -> Top To Bottom
        rtf: Return to first, if its True it flips to the first page 
             when next page requested at the last page
        """
        # First initialize, QPageWidget is based on QScrollArea
        QScrollArea.__init__(self, parent)

        # Properties for QScrollArea
        self.setFrameShape(QFrame.NoFrame)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setWidgetResizable(True)

        # Main widget, which stores all Pages in it
        self.widget = QWidget(self)

        # Layout based on QBoxLayout which supports Vertical or Horizontal layout
        if direction == "ltr":
            self.layout = QBoxLayout(QBoxLayout.LeftToRight, self.widget)
            self.__scrollBar = self.horizontalScrollBar()
            self.__base_value = self.width
        else:
            self.layout = QBoxLayout(QBoxLayout.TopToBottom, self.widget)
            self.__scrollBar = self.verticalScrollBar()
            self.__base_value = self.height
        self.layout.setSpacing(0)
        self.layout.setMargin(0)

        # Return to first
        self.__return_to_first = rtf

        # TMP_PAGE, its using as last page in stack
        # A workaround for a QScrollArea bug
        self.__tmp_page = Page(QWidget(self.widget))
        self.__pages = [self.__tmp_page]
        self.__current = 0
        self.__last = 0

        # Set main widget
        self.setWidget(self.widget)

        # Animation TimeLine
        self.__timeline = QTimeLine()
        self.__timeline.setUpdateInterval(2)

        # Updates scrollbar position when frame changed
        self.__timeline.frameChanged.connect(lambda x: self.__scrollBar.setValue(x))

        # End of the animation
        self.__timeline.finished.connect(self._animateFinished)

        # Initialize animation
        self.setAnimation()
        self.setDuration()
Ejemplo n.º 12
0
class Win(QMainWindow):
    def __init__(self, parent=None):
        super(Win, self).__init__(parent)
        self.player = None
        # args
        parser = argparse.ArgumentParser(description='BBC radio player')
        parser.add_argument('-p', '--player', default='vlc')
        parser.add_argument('player_args', nargs='*')
        args = parser.parse_args()
        self.player_prog = args.player
        self.player_args = args.player_args
        # UI
        self.setWindowTitle(WIN_TITLE)
        self.setMinimumSize(300, 600)
        self.scroll_area = QScrollArea()
        self.widget = QWidget()
        self.layout = QVBoxLayout()
        self.widget.setLayout(self.layout)
        self.scroll_area.setWidgetResizable(True)
        self.scroll_area.setWidget(self.widget)
        self.setCentralWidget(self.scroll_area)
        for name, url in STATIONS:
            button = QPushButton(name.replace('&', '&&'))
            button.args = {
                'name': name,
                'url': url,
            }
            button.clicked.connect(self.listen)
            self.layout.addWidget(button)
        # timer
        self.timer = QTimer()
        self.timer.timeout.connect(self.check_player)

    def listen(self):
        pressed_button = self.sender()
        for button in self.widget.findChildren(QPushButton):
            if button != pressed_button and not button.isEnabled():
                button.setEnabled(True)
                break
        pressed_button.setEnabled(False)
        # stop the running player instance before starting another one
        if self.player:
            if self.player.poll() is None:
                self.player.terminate()
                self.player.wait()
        cmd = [self.player_prog]
        cmd.extend(self.player_args)
        cmd.append(pressed_button.args['url'])
        try:
            self.player = subprocess.Popen(cmd)
        except Exception, e:
            msg_box = QMessageBox()
            msg_box.setText('Couldn\'t launch\n"%s"' % ' '.join(cmd))
            msg_box.setInformativeText(unicode(e))
            msg_box.exec_()
            pressed_button.setEnabled(True)
        self.setWindowTitle('%s - %s' % (pressed_button.args['name'], WIN_TITLE))
        self.timer.start(200)
Ejemplo n.º 13
0
 def __init__(self, dialog):
     super(ScrolledPage, self).__init__(dialog)
     layout = QVBoxLayout(margin=0, spacing=0)
     self.setLayout(layout)
     scrollarea = QScrollArea(frameWidth=0, frameShape=QScrollArea.NoFrame)
     layout.addWidget(scrollarea)
     self.scrolledWidget = QWidget(scrollarea)
     scrollarea.setWidget(self.scrolledWidget)
     scrollarea.setWidgetResizable(True)
Ejemplo n.º 14
0
 def __init__(self, clearMouseOver, parent = None):
    QScrollArea.__init__(self, parent)
    self.clearMouseOver = clearMouseOver
    self.mouseOver = False
    
    self.widget = QWidget() # Just adding the layout directly doesn't work right, so wrap it in a QWidget
    self.setWidget(self.widget)
    self.setWidgetResizable(True)
    self.setMouseTracking(True)
    self.createLayout()
Ejemplo n.º 15
0
 def widgetFrame(self):
     """Create main display widget.
     """
     vbox = QVBoxLayout()
     scroll = QScrollArea()
     scroll.setAlignment(QtCore.Qt.AlignCenter)
     self.mediaLabel = QLabel(self)
     scroll.setWidget(self.mediaLabel)
     vbox.addWidget(scroll)
     return vbox
    def __init__(self, plotWindow, config):
        QScrollArea.__init__(self)
        self.widget = QWidget()
        self.clayout = QGridLayout()

        self.plotWindow = plotWindow
        self.config = config
        self.getGroupbox()

        self.setWidgetResizable(True)
        self.setWidget(self.widget)
Ejemplo n.º 17
0
class GridScrollTab(QObject):
	def __init__(self) -> None:
		super(GridScrollTab, self).__init__()
		
		self.model = None
		
		self.scroller = QScrollArea()
		self.widget = QWidget()
		self.layout = QGridLayout()
		self.layout.setSizeConstraint(QLayout.SetMinAndMaxSize)
		self.widget.setLayout(self.layout)
		self.scroller.setWidget(self.widget)
    def initUI(self, data, complete, back):
        self.completeButtonClick = complete
        self.backButtonClick = back

        main_layout = QHBoxLayout()

        self.touch_circuit_button = QPushButton("Touch circuit")
        self.drill_mode_button = QPushButton("Drill positioning mode")
        self.drill_mode_button.setCheckable(True)
        self.remove_mode_button = QPushButton("Remove mode")
        self.remove_mode_button.setCheckable(True)
        self.get_coordinate_button = QPushButton("Get coordinate from drill")
        self.complete_button = QPushButton("Complete")
        self.back_button = QPushButton("Back")

        self.touch_circuit_button.clicked.connect(self.touchCircuit)
        self.get_coordinate_button.clicked.connect(self.getCoordinateFromDrill)
        self.remove_mode_button.clicked[bool].connect(self.toggleRemoveMode)
        self.drill_mode_button.clicked[bool].connect(self.toggleDrillPositioningMode)

        if self.completeButtonClick is not None:
            self.complete_button.clicked.connect(self.handleCompleteButtonClick)
        if self.backButtonClick is not None:
            self.back_button.clicked.connect(self.backButtonClick)

        toolbar = QToolbar()
        toolbar.addWidgetToToolbar(self.drill_mode_button)
        toolbar.addWidgetToToolbar(self.touch_circuit_button)
        toolbar.addWidgetToToolbar(self.get_coordinate_button)
        toolbar.addWidgetToToolbar(self.remove_mode_button)
        toolbar.addWidgetToToolbar(self.complete_button)
        toolbar.addWidgetToToolbar(self.back_button)
        toolbar.addStretch(1)

        self.markable_area = QMarksArea()
        self.markable_area.setMaximumSize(data.image_width, data.image_height)
        self.markable_area.loadImage(data.image_path)
        self.markable_area.setMarksCountLimit(2)
        self.markable_area.setBrushColor(QColor(constants.defaultBrushColor))

        viewer = QViewer()
        viewer.setView(self.markable_area)
        viewer_scroll = QScrollArea()
        viewer_scroll.setWidget(viewer)
        viewer_scroll.setWidgetResizable(True)

        main_layout.addWidget(toolbar)
        main_layout.addWidget(viewer_scroll)
        main_layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(main_layout)
Ejemplo n.º 19
0
    def __init__(self, parent):
        QScrollArea.__init__(self, parent)

        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

        self.keyboard = PixmapKeyboard(self)
        self.keyboard.setMode(PixmapKeyboard.HORIZONTAL)
        self.keyboard.setOctaves(10)
        self.setWidget(self.keyboard)

        self.setEnabled(False)
        self.setFixedHeight(self.keyboard.height() + self.horizontalScrollBar().height()/2 + 2)

        QTimer.singleShot(0, self.slot_initScrollbarValue)
Ejemplo n.º 20
0
    def __init__(self):        
        super(MainWindow, self).__init__()

        centralWidget = QWidget()
        self.setCentralWidget(centralWidget)

        self.glWidget = GLWidget()
        self.pixmapLabel = QLabel()

        self.glWidgetArea = QScrollArea()
        self.glWidgetArea.setWidget(self.glWidget)
        self.glWidgetArea.setWidgetResizable(True)
        self.glWidgetArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.glWidgetArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.glWidgetArea.setSizePolicy(QSizePolicy.Ignored,
                QSizePolicy.Ignored)
        self.glWidgetArea.setMinimumSize(50, 50)

        self.pixmapLabelArea = QScrollArea()
        self.pixmapLabelArea.setWidget(self.pixmapLabel)
        self.pixmapLabelArea.setSizePolicy(QSizePolicy.Ignored,
                QSizePolicy.Ignored)
        self.pixmapLabelArea.setMinimumSize(50, 50)

        xSlider = self.createSlider(self.glWidget.xRotationChanged,
                self.glWidget.setXRotation)
        ySlider = self.createSlider(self.glWidget.yRotationChanged,
                self.glWidget.setYRotation)
        zSlider = self.createSlider(self.glWidget.zRotationChanged,
                self.glWidget.setZRotation)

        self.createActions()
        self.createMenus()

        centralLayout = QGridLayout()
        centralLayout.addWidget(self.glWidgetArea, 0, 0)
        centralLayout.addWidget(self.pixmapLabelArea, 0, 1)
        centralLayout.addWidget(xSlider, 1, 0, 1, 2)
        centralLayout.addWidget(ySlider, 2, 0, 1, 2)
        centralLayout.addWidget(zSlider, 3, 0, 1, 2)
        centralWidget.setLayout(centralLayout)

        xSlider.setValue(15 * 16)
        ySlider.setValue(345 * 16)
        zSlider.setValue(0 * 16)

        self.setWindowTitle("Grabber")
        self.resize(400, 300)
Ejemplo n.º 21
0
    def __init__(self, parent=None):
        super(ResultHandler, self).__init__()
        self.setWindowTitle('Dash results')
        self.control_label = QLabel()
        self.rendered_label = QLabel()
        self.diff_label = QLabel()

        self.mask_label = QLabel()
        self.new_mask_label = QLabel()

        self.scrollArea = QScrollArea()
        self.widget = QWidget()

        self.test_name_label = QLabel()
        grid = QGridLayout()
        grid.addWidget(self.test_name_label, 0, 0)
        grid.addWidget(QLabel('Control'), 1, 0)
        grid.addWidget(QLabel('Rendered'), 1, 1)
        grid.addWidget(QLabel('Difference'), 1, 2)
        grid.addWidget(self.control_label, 2, 0)
        grid.addWidget(self.rendered_label, 2, 1)
        grid.addWidget(self.diff_label, 2, 2)
        grid.addWidget(QLabel('Current Mask'), 3, 0)
        grid.addWidget(QLabel('New Mask'), 3, 1)
        grid.addWidget(self.mask_label, 4, 0)
        grid.addWidget(self.new_mask_label, 4, 1)

        self.widget.setLayout(grid)
        self.scrollArea.setWidget(self.widget)
        v_layout = QVBoxLayout()
        v_layout.addWidget(self.scrollArea, 1)

        next_image_button = QPushButton()
        next_image_button.setText('Skip')
        next_image_button.pressed.connect(self.load_next)

        self.overload_spin = QDoubleSpinBox()
        self.overload_spin.setMinimum(1)
        self.overload_spin.setMaximum(255)
        self.overload_spin.setValue(1)
        self.overload_spin.valueChanged.connect(lambda: save_mask_button.setEnabled(False))

        preview_mask_button = QPushButton()
        preview_mask_button.setText('Preview New Mask')
        preview_mask_button.pressed.connect(self.preview_mask)
        preview_mask_button.pressed.connect(lambda: save_mask_button.setEnabled(True))

        save_mask_button = QPushButton()
        save_mask_button.setText('Save New Mask')
        save_mask_button.pressed.connect(self.save_mask)

        button_layout = QHBoxLayout()
        button_layout.addWidget(next_image_button)
        button_layout.addWidget(QLabel('Mask diff multiplier:'))
        button_layout.addWidget(self.overload_spin)
        button_layout.addWidget(preview_mask_button)
        button_layout.addWidget(save_mask_button)
        button_layout.addStretch()
        v_layout.addLayout(button_layout)
        self.setLayout(v_layout)
Ejemplo n.º 22
0
    def initUI(self):
        """ Init user interface. """
        # use QVBoxLayout to store two layouts vertically
        self.vl = QVBoxLayout()

        # widget for scrollArea
        self.topWidget = QWidget()
        self.grid = QGridLayout()
        self.topWidget.setLayout(self.grid)
        self.vl.addWidget(self.topWidget)

        # layout for filter
        self.filter = QHBoxLayout()
        # draw filter widgets
        self.drawFilter()
        spacer = QSpacerItem(10, 0, vPolicy=QSizePolicy.MinimumExpanding)
        self.vl.addItem(spacer)
        self.vl.addLayout(self.filter)

        self.setLayout(self.vl)
        self.rows = []

        self.taskArea = QScrollArea(self)
        self.taskArea.setWidget(self.topWidget)
        self.taskArea.setWidgetResizable(True)
        self.taskArea.resize(500, 350)
        self.resize(500, 395)
        self.setMinimumSize(460, 90)
        self.filterApply()
        self.show()
        self.move(QApplication.desktop().screen().rect().center() -
                  self.rect().center())
        self.setWindowTitle(conf.lang.EDIT_TITLE)
        iconEdit = Icon(byte=icons.edit).convertToIcon().getIcon()
        self.setWindowIcon(iconEdit)
Ejemplo n.º 23
0
    def __init__(self, parent=None):
        super(GlyphCollectionWidget, self).__init__(parent)
        self.setAttribute(Qt.WA_KeyCompression)
        self._glyphs = []
        # TODO: hide behind a façade
        self.squareSize = 56
        self._columns = 10
        self._selection = set()
        self._oldSelection = None
        self._lastSelectedCell = None

        self.characterSelectedCallback = None
        self.doubleClickCallback = None
        self.updateCurrentGlyph = False
        self._maybeDragPosition = None

        self.setFocusPolicy(Qt.ClickFocus)
        self._currentDropIndex = None
        self._scrollArea = QScrollArea(parent)
        self._scrollArea.dragEnterEvent = self.pipeDragEnterEvent
        self._scrollArea.dragMoveEvent = self.pipeDragMoveEvent
        self._scrollArea.dragLeaveEvent = self.pipeDragLeaveEvent
        self._scrollArea.dropEvent = self.pipeDropEvent
        self._scrollArea.setAcceptDrops(True)
        self._scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self._scrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self._scrollArea.setWidget(self)
Ejemplo n.º 24
0
    def __init__(self, font, pointSize=defaultPointSize, parent=None):
        super(GlyphsCanvas, self).__init__(parent)
        self.setAttribute(Qt.WA_KeyCompression)
        # TODO: should we take focus by tabbing
        self.setFocusPolicy(Qt.ClickFocus)
        # XXX: make canvas font-agnostic as in defconAppkit and use
        # glyph.getParent() instead
        self.font = font
        self.fetchFontMetrics()
        self.glyphs = []
        self.ptSize = pointSize
        self.calculateScale()
        self.padding = 10
        self._editing = False
        self._showKerning = False
        self._showMetrics = False
        self._verticalFlip = False
        self._lineHeight = 1.1
        self._positions = None
        self._selected = None
        self.doubleClickCallback = None
        self.pointSizeChangedCallback = None
        self.selectionChangedCallback = None

        self._wrapLines = True
        self._scrollArea = QScrollArea(self.parent())
        self._scrollArea.resizeEvent = self.resizeEvent
        self._scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self._scrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self._scrollArea.setWidget(self)
        self.resize(581, 400)
Ejemplo n.º 25
0
 def __init__(self, parent=None):
     super(Win, self).__init__(parent)
     self.player = None
     # args
     parser = argparse.ArgumentParser(description='BBC radio player')
     parser.add_argument('-p', '--player', default='vlc')
     parser.add_argument('player_args', nargs='*')
     args = parser.parse_args()
     self.player_prog = args.player
     self.player_args = args.player_args
     # UI
     self.setWindowTitle(WIN_TITLE)
     self.setMinimumSize(300, 600)
     self.scroll_area = QScrollArea()
     self.widget = QWidget()
     self.layout = QVBoxLayout()
     self.widget.setLayout(self.layout)
     self.scroll_area.setWidgetResizable(True)
     self.scroll_area.setWidget(self.widget)
     self.setCentralWidget(self.scroll_area)
     for name, url in STATIONS:
         button = QPushButton(name.replace('&', '&&'))
         button.args = {
             'name': name,
             'url': url,
         }
         button.clicked.connect(self.listen)
         self.layout.addWidget(button)
     # timer
     self.timer = QTimer()
     self.timer.timeout.connect(self.check_player)
Ejemplo n.º 26
0
    def __init__(self):
        super(ImageViewer, self).__init__()

        self.printer = QPrinter()
        self.scaleFactor = 0.0

        self.imageLabel = QLabel()
        self.imageLabel.setBackgroundRole(QPalette.Base)
        self.imageLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        self.imageLabel.setScaledContents(True)
        self.scrollArea = QScrollArea()
        self.scrollArea.setBackgroundRole(QPalette.Dark)
        self.scrollArea.setWidget(self.imageLabel)
        self.setCentralWidget(self.scrollArea)

        self.createActions()
        self.createMenus()

        self.setWindowTitle("Image Viewer")
        self.resize(500, 100)
        self.resizeEvent=self.get_resize
        self.width=self.size().width()
        self.height = self.size().height()
        self.image_obj = None
        self.flag=0
Ejemplo n.º 27
0
    def __init__(self, parent):
        QVBoxLayout.__init__(self, parent)

        self.scroll_area = QScrollArea()

        self.grid_frame = QFrame(self.scroll_area)

        self.grid_layout = QGridLayout(self.grid_frame)

        self.scroll_area.setWidget(self.grid_frame)
        self.scroll_area.setWidgetResizable(True)
        self.scroll_area.setBackgroundRole(QPalette.Light)

        self.addWidget(self.scroll_area)

        self.current_column = 0

        self.current_row = 0

        self.initial_grid = True

        self.max_columns = 5

        self.current_width = 0

        self.child_widgets = list()
Ejemplo n.º 28
0
   def initUI(self):
      self.content = QWidget()

      self.hbox = QHBoxLayout(self.content)
      self.setCentralWidget(self.content)

      self.friend_list = QListWidget()
      self.friend_list.itemClicked.connect(self.friendClicked)

      self.message_scroll = QScrollArea()
      self.message_scroll.setWidgetResizable(True)
      #TODO have a setting to disable this
      self.message_scroll.verticalScrollBar().rangeChanged.connect(self.scrollBottom)

      self.message_input = MessageInput()
      self.message_input.sendMessage.connect(self.sendMessage)

      self.message_split = QSplitter(Qt.Vertical)
      self.message_split.addWidget(self.message_scroll)
      self.message_split.addWidget(self.message_input)

      self.main_split = QSplitter(Qt.Horizontal)
      self.main_split.addWidget(self.friend_list)
      self.main_split.addWidget(self.message_split)

      self.hbox.addWidget(self.main_split)

      self.show()
Ejemplo n.º 29
0
Archivo: qtx.py Proyecto: winks/pynt
  def bootstrap(self):
    self.no_margin = QMargins(0, 0, 0, 0)
    self.app = App()
    self.app.setWindowIcon(QIcon(self.ICON_APP))
    if platform.system() == 'Windows':
      myappid = 'f5n.pynt.alpha'
      ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)

    self.scroll_area = QScrollArea()
    self.scroll_area.setContentsMargins(self.no_margin)
    self.scroll_area.setBackgroundRole(QPalette.Dark);
    self.scroll_area.setWidgetResizable(True)
    self.scroll_area.setWindowTitle(self.WINDOW_TITLE)

    self.main_layout = QVBoxLayout()
    self.main_layout.setSpacing(0)
    self.main_layout.setContentsMargins(self.no_margin)
    self.main_layout.addWidget(self.scroll_area)

    self.contents = QWidget()
    self.contents.setContentsMargins(self.no_margin)
    self.contents.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
    #self.contents.setScaledContents(True)

    self.scroll_area.setWidget(self.contents)

    self.layout = QVBoxLayout(self.contents)
    self.layout.setSizeConstraint(QLayout.SetMinimumSize)

    return self
Ejemplo n.º 30
0
    def __init__(self, initial='', parent=None):
        super().__init__(parent)

        self.setWindowModality(QtCore.Qt.ApplicationModal)
        self.setMaximumSize(400, 230)
        self.setMinimumSize(400, 230)
        self.resize(400, 230)

        self.scrollArea = QScrollArea(self)
        self.scrollArea.setGeometry(QtCore.QRect(5, 5, 390, 190))
        self.scrollArea.setWidgetResizable(True)

        self.plainTextEdit = QPlainTextEdit()
        self.plainTextEdit.setGeometry(QtCore.QRect(0, 0, 390, 190))
        self.plainTextEdit.setPlainText(initial)

        self.scrollArea.setWidget(self.plainTextEdit)

        self.acceptButton = QPushButton(self)
        self.acceptButton.setGeometry(QtCore.QRect(280, 200, 100, 25))
        self.acceptButton.setText("Ok")

        self.rejectButton = QPushButton(self)
        self.rejectButton.setGeometry(QtCore.QRect(160, 200, 100, 25))
        self.rejectButton.setText("Cancel")

        self.rejectButton.clicked.connect(self.reject)
        self.acceptButton.clicked.connect(self.accept)
Ejemplo n.º 31
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        self.centralwidget = QWidget(self)
        self.mainLayout = QVBoxLayout(self.centralwidget)

        self.scrollArea = QScrollArea(self.centralwidget)
        self.scrollAreaWidgetContents = QWidget()
        self.listWidget = QtWidgets.QListWidget(self.scrollAreaWidgetContents)

        self.label = QLabel(self.centralwidget)

        self.chooseButton = self.addButton("Wybierz plik", 12, 330, 420, 130, 50)
        self.okButton = self.addButton("Zatwierdź", 14, 200, 630, 130, 50)
        self.saveButton = self.addButton("Zapisz", 16, 700, 640, 130, 50)

        self.setupUi()

    def setupUi(self):
        self.setObjectName("MainWindow")
        self.resize(1100, 750)
        self.setDocumentMode(False)
        self.setDockNestingEnabled(False)

        self.centralwidget.setObjectName("centralwidget")

        self.scrollArea.setGeometry(QtCore.QRect(100, 180, 361, 161))
        self.scrollArea.setMouseTracking(True)
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setObjectName("scrollArea")

        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 359, 159))
        self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")

        self.listWidget.setGeometry(QtCore.QRect(0, 0, 361, 161))
        self.listWidget.setFont(settingFont(16))
        self.listWidget.setMouseTracking(True)
        self.listWidget.setObjectName("listWidget")

        for x in range(0, 8):
            item = QListWidgetItem()
            item.setText("pacjent00" + str(x + 1))
            self.listWidget.addItem(item)

        self.scrollArea.setWidget(self.scrollAreaWidgetContents)

        self.label.setGeometry(QtCore.QRect(180, 20, 731, 131))
        self.label.setFont(settingFont(28))
        self.label.setAcceptDrops(False)
        self.label.setLayoutDirection(QtCore.Qt.LeftToRight)
        self.label.setAutoFillBackground(False)
        self.label.setScaledContents(False)
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setWordWrap(True)
        self.label.setObjectName("label")

        self.textEdit = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit.setGeometry(QtCore.QRect(100, 370, 361, 41))
        self.textEdit.setFont(settingFont(13))
        self.textEdit.setText("Wprowadź scieżkę pliku wraz z jego nazwą")

        self.ekgView = QtWidgets.QGraphicsView(self.centralwidget)
        self.ekgView.setGeometry(QtCore.QRect(530, 180, 461, 161))
        self.ekgView.setObjectName("ekgView")

        self.vectroView = QtWidgets.QGraphicsView(self.centralwidget)
        self.vectroView.setGeometry(QtCore.QRect(530, 370, 461, 231))
        self.vectroView.setObjectName("vectroView")

        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(540, 190, 41, 21))
        self.label_2.setFont(settingFont(14, True))
        self.label_2.setObjectName("label_2")

        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(540, 380, 201, 21))
        self.label_3.setFont(settingFont(14, True))
        self.label_3.setObjectName("label_3")

        self.setCentralWidget(self.centralwidget)

        self.menubar = QtWidgets.QMenuBar(self)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1071, 21))
        self.menubar.setObjectName("menubar")

        self.menuFile = QtWidgets.QMenu(self.menubar)
        self.menuFile.setObjectName("menuFile")

        self.menuAbout = QtWidgets.QMenu(self.menubar)
        self.menuAbout.setObjectName("menuAbout")

        self.setMenuBar(self.menubar)

        self.statusbar = QtWidgets.QStatusBar(self)
        self.statusbar.setObjectName("statusbar")
        self.setStatusBar(self.statusbar)

        self.actionRelease = QtWidgets.QAction(self)
        self.actionRelease.setObjectName("actionRelease")

        self.actionInfo = QtWidgets.QAction(self)
        self.actionInfo.setObjectName("actionInfo")

        self.actionRelease_2 = QtWidgets.QAction(self)
        self.actionRelease_2.setObjectName("actionRelease_2")

        self.actionAuthors = QtWidgets.QAction(self)
        self.actionAuthors.setObjectName("actionAuthors")

        self.actionAdd_patient = QtWidgets.QAction(self)
        self.actionAdd_patient.setShortcutContext(QtCore.Qt.ApplicationShortcut)
        self.actionAdd_patient.setObjectName("actionAdd_patient")

        self.menuFile.addAction(self.actionAdd_patient)

        self.menuAbout.addAction(self.actionInfo)
        self.menuAbout.addAction(self.actionRelease_2)
        self.menuAbout.addAction(self.actionAuthors)

        self.menubar.addAction(self.menuFile.menuAction())
        self.menubar.addAction(self.menuAbout.menuAction())

        self.retranslateUi(self)
        QtCore.QMetaObject.connectSlotsByName(self)

        # dodac wszystko do mainLayout
        #
        self.mainLayout.setAlignment(QtCore.Qt.AlignCenter)
        self.setCentralWidget(self.centralwidget)

        # otwarcie exploratora dla proby
        self.actionAdd_patient.triggered.connect(lambda: subprocess.Popen('explorer'))

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Wektrokardiogram"))
        __sortingEnabled = self.listWidget.isSortingEnabled()
        self.listWidget.setSortingEnabled(False)

        self.listWidget.setSortingEnabled(__sortingEnabled)
        self.label.setText(_translate("MainWindow", "Oprogramowanie do wczytywania oraz prezentacji wektrokardiogramu"))

        self.label_2.setText(_translate("MainWindow", "EKG"))
        self.label_3.setText(_translate("MainWindow", "WEKTROKARDIOGRAM"))
        self.menuFile.setTitle(_translate("MainWindow", "File"))
        self.menuAbout.setTitle(_translate("MainWindow", "About"))
        self.actionRelease.setText(_translate("MainWindow", "Release"))
        self.actionInfo.setText(_translate("MainWindow", "Info"))
        self.actionRelease_2.setText(_translate("MainWindow", "Release"))
        self.actionAuthors.setText(_translate("MainWindow", "Authors"))
        self.actionAdd_patient.setText(_translate("MainWindow", "Add patient"))
        self.actionAdd_patient.setShortcut(_translate("MainWindow", "Ctrl+N"))

    def addButton(self, text, fontSize, xCoord, yCoord, width, heigh):
        pushButton = QtWidgets.QPushButton(self.centralwidget)
        pushButton.setGeometry(QtCore.QRect(xCoord, yCoord, width, heigh))
        pushButton.setFont(settingFont(fontSize))
        pushButton.setText(text)
        return pushButton
Ejemplo n.º 32
0
    def ui(self):
        scroll = QScrollArea()
        scroll.setStyleSheet("background: #fafafa;")
        layout = QVBoxLayout(self)
        layout.setAlignment(Qt.AlignHCenter | Qt.AlignTop)

        width = 720

        path = abs_path('icons/banner 2.png')
        banner = Banner(
            path,
            width=width,
            height=155,
            title="PDASH",
            subtitle=
            "Parallel Distributed Architecture for Data Storage and Sharing")
        banner.setObjectName('banner')

        layout.addWidget(banner)

        # add market title
        layout.addSpacing(15)
        layout.addWidget(Builder().text("Market Products").style(
            "font-size:24px;color:#333333;").build())

        layout.addSpacing(15)
        self.loading = Loading(text='Loading')
        layout.addWidget(self.loading)

        # Product List
        pdsWidget = ProductList(self.products, scroll=False)
        pdsWidget.setObjectName('products_list')
        pdsWidget.setMinimumWidth(width)
        pdsWidget.setMaximumWidth(width)

        layout.addWidget(pdsWidget)
        layout.addStretch(1)
        scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        scroll.setWidgetResizable(True)
        wid = QWidget()
        wid.setLayout(layout)
        wid.setContentsMargins(0, 0, 0, 0)
        scroll.setWidget(wid)

        _layout = QVBoxLayout()
        _layout.setAlignment(Qt.AlignTop)
        _layout.addWidget(scroll)
        # add spacing with bottom
        _layout.addSpacing(30)
        wid.setStyleSheet("""
        """)
        return _layout
Ejemplo n.º 33
0
class ModelViewAction(QMainWindow):
    """Model Create"""
    def __init__(self, attrData, config):
        super(ModelViewAction, self).__init__()

        print(attrData)
        self.attrData = attrData

        self.npz_file = attrData.get('Dataset_Path')
        self.mod_file = attrData.get('Model_Path')

        self.img_num = int(attrData.get('Images'))
        self.img_row = int(attrData.get('Images_Row'))
        self.img_col = int(attrData.get('Images_Column'))

        # loading data
        print("Loading previously created data...")
        self.data = np.load(self.npz_file)

        # loading the previous model
        print("Loading Model")
        self.model = load_model(self.mod_file)

        # making a prediction on test dataset
        self.y_pred = self.model.predict(self.data["x_test"])

        self.gridLayout = QGridLayout()
        self.window = QWidget()
        self.window.setContentsMargins(0, 0, 0, 0)
        self.window.setLayout(self.gridLayout)

        self.images = []
        self.buildLayout(self.img_num, self.img_row, self.img_col)
        self.window.update()

    def buildLayout(self, img_num, img_row, img_col):
        for i in range(img_row):
            l = []
            for j in range(img_col):
                img_num += 1

                self.widget = QWidget()
                self.widget.setContentsMargins(0, 0, 0, 0)
                self.label = QLabel(self.widget)
                self.image = self.ColourMap(img_num)
                self.label.setPixmap(self.image)
                self.label.setContentsMargins(0, 0, 0, 0)
                self.label.setFixedSize(100, 100)
                l.append(self.label)
                self.gridLayout.addWidget(self.label, i, j)
                self.gridLayout.setColumnMinimumWidth(j, 0)
                self.gridLayout.setContentsMargins(0, 0, 0, 0)
                self.gridLayout.setSpacing(0)

            self.images.append(l)
            self.gridLayout.setRowMinimumHeight(i, 0)

        self.scroll = QScrollArea()
        self.scroll.setMinimumHeight(1000)
        self.scroll.setContentsMargins(0, 0, 0, 0)
        self.scroll.setWidget(self.window)
        self.scroll.setWidgetResizable(True)
        self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.scroll.update()

        self.setCentralWidget(self.scroll)

    def ColourMap(self, img):

        sp = SubplotParams(left=0., bottom=0., right=1., top=1.)
        fig = Figure((1, 1), subplotpars=sp)
        canvas = FigureCanvas(fig)
        ax = fig.add_subplot(111)
        #test = self.numpy2pil(self.y_pred)
        ax.imshow(self.y_pred[img, img:, img:, 0])
        ax.set_axis_off()
        canvas.draw()
        size = canvas.size()
        width, height = size.width(), size.height()

        #RGB_img = cv2.cvtColor(canvas.buffer_rgba(), cv2.COLOR_BGR2RGB)

        img = QImage(canvas.buffer_rgba(), width, height, QImage.Format_ARGB32)
        return QPixmap(img)

    def numpy2pil(np_array: np.ndarray):
        """
        Convert an HxWx3 numpy array into an RGB Image
        """

        assert_msg = 'Input shall be a HxWx3 ndarray'
        assert isinstance(np_array, np.ndarray), assert_msg
        assert len(np_array.shape) == 3, assert_msg
        assert np_array.shape[2] == 3, assert_msg

        img = Image.fromarray(np_array, 'RGB')
        return img
Ejemplo n.º 34
0
class Example(QWidget):
    def __init__(self):
        super().__init__()

        self.initUI()

    def connect(self):
        if self.IPbox.text() == "":
            text, ok = QInputDialog.getText(self, 'Input Dialog', '输入IP:')
            if ok:
                self.IPbox.setText(str(text))


#        if self.usernamebox.text() == "":
#            text, ok = QInputDialog.getText(self, 'Input Dialog', '输入用户名:')
#            if ok:
#                self.usernamebox.setText(str(text))
#        if self.passwordbox.text() == "":
#            text, ok = QInputDialog.getText(self, 'Input Dialog', '输入密码:')
#            if ok:
#                self.passwordbox.setText(str(text))
#        if self.ethbox.text() == "":
#            text, ok = QInputDialog.getText(self, 'Input Dialog', '输入网口号:(eg:eth1)')
#            if ok:
#                self.ethbox.setText(str(text))
        self.IP = self.IPbox.text()
        self.username = self.usernamebox.text()
        self.password = self.passwordbox.text()
        self.eth = self.ethbox.text()
        QMessageBox.information(self, "", "需要一段时间,请等待")
        #a, b = subprocess.getstatusoutput('ping ' + self.IP)  # a是退出状态 b是输出的结果
        self.thread_connect = MyThread(re='ping  -t 100 -c 2 ' +
                                       self.IP)  # 创建一个线程 发送cmd
        self.thread_connect.sec_changed_signal.connect(
            self.update_state_connect)  # cmd线程发过来的信号挂接到槽:update_state
        #self.thread2.sec_changed_signal.connect(self.update_time)  # 计时线程发过来的信号挂接到槽:update_time
        self.thread_connect.start()

    def update_state_connect(self, b):
        self.resultbox.setText(b)
        if "ms" in b and "100% packet loss" not in b:
            QMessageBox.information(
                self,  # 使用infomation信息框
                "注意",
                "连接成功")
        else:
            QMessageBox.information(self, "注意", "连接失败 请检查IP设置")
        self.thread_connect.terminate()

    def update(self):
        QApplication.processEvents()

    def read_json(self):
        global config_dic
        global res_cmd
        global send_list
        global tab_name
        global pcap_path
        global twolineflag

        try:
            fname = QFileDialog.getOpenFileName(
                self,
                "选取文件",
                "./",  # 起始路径
                "配置文件 (*.json)")  # 设置文件扩展名过滤,用双分号间隔

            with open(fname[0], 'r') as load_f:
                config_dic = json.load(load_f)
                send_list = {}
                res_cmd = ""
                tab_name = []
                pcap_path = ""
                res_cmd = fname[0]
                self.tab.clear()
                for test_type in config_dic.keys():
                    send_list[test_type] = []
                    tab_name.append(test_type)
                    self.tab.test_type = Checkboxlist(test_type)
                    l = int(len(test_type) / 2)
                    s = test_type[0:l] + '\n' * twolineflag + test_type[l:]
                    self.tab.addTab(self.tab.test_type, s)
                self.update()
        except:
            return 1

    def initUI(self):
        # 读取配置文件
        global config_dic
        global twolineflag
        try:
            with open('config.json', 'r') as load_f:
                config_dic = json.load(load_f)
        except:
            config_dic = config_dic
            QMessageBox.information(
                self,  # 使用infomation信息框
                "注意",
                "未找到配置文件 请手动选择")
            self.read_json()
            # 初始化连接
        self.IPbox = QLineEdit()
        #self.IPbox.setText("192.168.201.129")
        self.re_num = 1
        self.usernamebox = QLineEdit()
        self.ethbox = QLineEdit()
        self.passwordbox = QLineEdit()
        self.connect_button = QPushButton("测试连接")
        self.update_button = QPushButton("更新配置")
        hbox1 = QHBoxLayout()
        hbox1.addWidget(QLabel("被测试IP:"))
        hbox1.addWidget(self.IPbox)
        hbox1.addWidget(self.connect_button)
        hbox1.addWidget(QLabel("      "))
        hbox1.addWidget(QLabel("本机用户名:"))
        hbox1.addWidget(self.usernamebox)
        hbox1.addWidget(QLabel("本机密码:"))
        hbox1.addWidget(self.passwordbox)
        hbox1.addWidget(QLabel("网口号:"))
        hbox1.addWidget(self.ethbox)

        hbox1.addWidget(self.update_button)

        self.connect_button.clicked.connect(self.connect)
        self.update_button.clicked.connect(self.read_json)

        # 中间

        self.topFiller = QWidget()
        self.topFiller.setMinimumSize(2500, 2000)  #######设置滚动条的尺寸
        self.tab = QTabWidget()
        for test_type in config_dic.keys():
            send_list[test_type] = []
            tab_name.append(test_type)

            self.tab.test_type = Checkboxlist(test_type)
            l = int(len(test_type) / 2)
            s = test_type[0:l] + '\n' * twolineflag + test_type[l:]
            self.tab.addTab(self.tab.test_type, s)
        # tab.tabBar().setFixedHeight(48)
        hbox2 = QHBoxLayout(self.topFiller)
        hbox2.addWidget(self.tab)
        #hbox2.addWidget(self.scroll)
        self.scroll = QScrollArea()
        self.scroll.setWidget(self.topFiller)

        # 辅助功能
        hbox3 = QHBoxLayout()
        hbox4 = QHBoxLayout()
        self.re_timebox = QSlider(Qt.Horizontal, self)
        self.re_timebox.setMinimum(1)
        self.re_timebox.setMaximum(1000)
        self.re_timebox.valueChanged[int].connect(self.changeValue)
        self.num = QLabel("1")
        self.fullspeed = QCheckBox("全速发送")
        hbox3.addWidget(self.fullspeed)  # -R

        hbox4.addWidget(QLabel("  重复次数:"))
        hbox4.addWidget(self.num)
        hbox4.addWidget(self.re_timebox)

        hbox3.addWidget(QLabel("  最大发包数量:"))
        self.maxpacknumbox = QLineEdit()  # -L
        hbox3.addWidget(self.maxpacknumbox)
        hbox3.addWidget(QLabel("  每秒发送报文数:"))
        self.packpsbox = QLineEdit()  # -p
        hbox3.addWidget(self.packpsbox)
        '''hbox3.addWidget(QLabel("  指定MTU:"))
        self.MTUbox = QLineEdit()  # -t
        hbox3.addWidget(self.MTUbox)'''

        hbox3.addWidget(QLabel("发包速度/Mbps:"))
        self.Mbpsbox = QLineEdit()
        hbox3.addWidget(self.Mbpsbox)

        # 开始测试
        self.start_button = QPushButton("开始发送数据包")
        self.start_button.clicked.connect(self.start_test)
        self.stop_button = QPushButton("停止发送数据包")
        self.stop_button.clicked.connect(self.stop_test)
        hbox5 = QHBoxLayout()
        hbox5.addWidget(self.start_button)
        hbox5.addWidget(self.stop_button)
        #        hbox5.addWidget(QLabel("                            time:"))
        #        self.timebox = QLineEdit()
        #        hbox5.addWidget(self.timebox)
        # 显示输出结果
        self.resultbox = QTextBrowser()

        vbox = QVBoxLayout()
        vbox.addLayout(hbox1)
        vbox.addWidget(QLabel("选择测试模式:"))

        #vbox.addLayout(hbox2)
        vbox.addWidget(self.scroll)
        vbox.addWidget(QLabel("可选项:"))
        vbox.addLayout(hbox3)
        vbox.addLayout(hbox4)

        vbox.addLayout(hbox5)
        vbox.addWidget(QLabel("状态提示信息:"))
        vbox.addWidget(self.resultbox)
        self.setLayout(vbox)
        # self.setGeometry(300, 300, 290, 150)
        self.setWindowTitle('tcpreplay_gui')
        self.show()

    def changeValue(self, value):
        self.num.setText(str(value))
        self.re_num = value

    def stop_test(self):
        if "数据包发送成功" not in self.resultbox.toPlainText(
        ) and " 默认发包速度下" in self.resultbox.toPlainText():
            try:
                self.thread.terminate()
                self.thread2.terminate()
                self.resultbox.setText("")
            except:
                self.resultbox.setText("")
        else:
            self.resultbox.setText("")

    def start_test(self):
        self.resultbox.setText("")

        # tcprewrite是否需要
        self.resultbox.setText("")
        # -i 设置eth端口
        if self.ethbox.text() == "":
            text, ok = QInputDialog.getText(self, 'Input Dialog',
                                            '输入网口号:(eg:eth1)')
            if ok:
                self.ethbox.setText(str(text))
        if self.passwordbox.text() == "":
            text, ok = QInputDialog.getText(self, 'Input Dialog', '输入密码')
            if ok:
                self.passwordbox.setText(str(text))
        re = "echo " + self.passwordbox.text(
        ) + "|sudo -S " + "tcpreplay -i " + self.ethbox.text() + " "
        # 最大速率发送 -t
        if self.fullspeed.isChecked():
            re += " -t "
        else:
            re = re
        # 重复次数
        if self.re_num > 1:
            re = re + "-l " + str(self.re_num) + " "
        ''''#制定MTU
        if not self.MTUbox.text()=="":
            re+=" - "+ self.MTUbox.text()+' ''' ''

        # 每秒发包数量
        if not self.packpsbox.text() == "":
            re += ' -p ' + self.packpsbox.text() + ' '
        # 发送速度MB/s
        if not self.Mbpsbox.text() == "":
            re += ' -M ' + self.Mbpsbox.text() + ' '
        # 最大发包数量
        if not self.maxpacknumbox.text() == "":
            re += ' -L ' + self.maxpacknumbox.text() + ' '
        # 数据包名称 路径应和json文件位置相同
        tabindex = self.tab.currentIndex()
        tn = (tab_name[tabindex])
        pcaplist = send_list[tn]
        if len(pcaplist) == 0:
            QMessageBox.information(
                self,  # 使用infomation信息框
                "注意",
                "请选择至少一个包")
            return
        if len(pcaplist) == 1:
            re += pcap_path + pcaplist[0]
        else:
            temp = re
            re = ""
            for i in pcaplist:
                re += temp + pcap_path + i + " &&"
            re = re[0:-2]

    # self.resultbox.setText(self.resultbox.toPlainText() + '\r\n' + re)
        self.starttime = time.time()
        self.resultbox.setText(self.resultbox.toPlainText() + '\r\n' +
                               "正在发送数据包 默认发包速度下可能需要较长时间 请耐心等待。。。")
        self.thread = MyThread(re=re)  # 创建一个线程 发送cmd
        self.thread2 = MyThread2(self.starttime)  # 创建一个线程 计时

        self.thread.sec_changed_signal.connect(
            self.update_state)  # cmd线程发过来的信号挂接到槽:update_state
        self.thread2.sec_changed_signal.connect(
            self.update_time)  # 计时线程发过来的信号挂接到槽:update_time
        self.thread.start()
        self.thread2.start()

    def update_state(self, b):
        if "Actual" in b:
            self.resultbox.setText("数据包发送成功!" + '\r\n结果统计信息:\r\n' +
                                   b[b.index("Actual"):])
        else:
            QMessageBox.information(
                self,  # 使用infomation信息框
                "注意",
                "未能成功发送 请检查网口设置与软件是否正确安装")

        # self.resultbox.setText(self.resultbox.toPlainText() + '\r\n' + b)
        self.thread.terminate()
        self.thread2.terminate()

    def update_time(self, a):
        self.resultbox.setText(self.resultbox.toPlainText() + '\r\n' +
                               "已用时间:" +
                               str(round(time.time() - self.starttime)) + "s")
Ejemplo n.º 35
0
class Resultados(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, simulacion, datos, *args, **kwargs):
        QtWidgets.QMainWindow.__init__(self, *args, **kwargs)
        self.simulacion = simulacion
        self.datos = datos
        self.ventanaPrincipal = None
        self.setupUi(self)
        self.center()

        # a figure instance to plot on
        self.figure = Figure(tight_layout=True, figsize=(10, 5))
        self.imgdata = BytesIO()

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)

        self.scroll = QScrollArea(self)
        self.scroll.setWidget(self.canvas)

        # set the layout
        self.layoutGrafico.addWidget(self.scroll)

        # Crear calculos
        self.calculo_sim = CalculosSimulacion(self.simulacion)
        self.calculo_sim.calcular_sim()

        self.modeloarbol = TreeModel(self.calculo_sim)
        self.treeView.setModel(self.modeloarbol)
        self.treeView.setHeaderHidden(True)
        self.treeView.expandAll()

        # Conectar el click de Finalizar con la accion
        self.bFinalizar.clicked.connect(self.click_finalizar)

        # Conectar el click de Volver con la accion
        self.bVolver.clicked.connect(self.click_menu_princ)

        # Conectar el click en el arbol para cargar tabla resultados
        self.treeView.clicked.connect(self.cargar_resultados)

        # Conectar el click en exportar con la accion
        self.bExportar.clicked.connect(self.click_exportar)

    def changeEvent(self, event, *args, **kwargs):
        if event.type() == QEvent.WindowStateChange:
            if self.tablaResultados.model() is not None:
                self.maximizar_headers()

    def center(self):
        # geometry of the main window
        qr = self.frameGeometry()

        # center point of screen
        cp = QDesktopWidget().availableGeometry().center()

        # move rectangle's center point to screen's center point
        qr.moveCenter(cp)

        # top left of rectangle becomes top left of window centering it
        self.move(qr.topLeft())

    def cargar_resultados(self, indice):
        elemento = indice.internalPointer().elemento
        modelo = None

        if isinstance(elemento, CalculosCorrida):
            self.figure.clf()
            modelo = ModeloCalcCorrida(elemento)
            modelo.headers[0] = self.datos.usuario + ' Nº'
            modelo.headers[8] = self.datos.servidor + ' Nº'
            g_c = GraficosCorrida(elemento, self.figure)
            g_c.graficar_corrida()
            self.canvas.draw()

        elif isinstance(elemento, CalculosExperimento):
            self.figure.clf()
            modelo = ModeloCalcExperimento(elemento)
            g_e = GraficosExp(elemento, self.figure)
            g_e.graficar_exp()
            self.canvas.draw()

        elif isinstance(elemento, CalculosSimulacion):
            self.figure.clf()
            modelo = ModeloCalcSimulacion(elemento)
            g_s = GraficarSim(elemento, self.figure)
            g_s.graficar_sim()
            self.canvas.draw()

        self.tablaResultados.setModel(modelo)
        self.tablaResultados.setItemDelegate(AlignDelegate())
        self.maximizar_headers()

    def maximizar_headers(self):
        header = self.tablaResultados.horizontalHeader()
        if self.isMaximized():
            for i in range(self.tablaResultados.model().columnCount()):
                header.setSectionResizeMode(i, QtWidgets.QHeaderView.Stretch)
        else:
            for i in range(self.tablaResultados.model().columnCount()):
                header.setSectionResizeMode(
                    i, QtWidgets.QHeaderView.ResizeToContents)

    def click_menu_princ(self):
        self.ventanaPrincipal = principal.Principal()
        self.ventanaPrincipal.show()
        self.hide()

    def click_exportar(self):
        name = 'resultados ' + self.datos.sistema
        name = name.replace(' ', '_').lower()
        options = QtWidgets.QFileDialog.Options()
        filename, _ = QtWidgets.QFileDialog.getSaveFileName(
            self.tablaResultados,
            'Exportar Resultados',
            name,
            ".xlsx(*.xlsx)",
            options=options)
        if not filename:
            return
        workbook = xlsxwriter.Workbook(filename)
        sheet1 = workbook.add_worksheet("Resultados")
        sheet2 = workbook.add_worksheet("Gráficos")
        self.add2(sheet1, sheet2, workbook)
        workbook.close()
        os.system('start ' + filename)

    def add2(self, sheet1, sheet2, workbook):
        # Guardar tabla de resultados
        parent = QModelIndex()
        headers = self.tablaResultados.model().headers
        cell_format = workbook.add_format({'bold': True})
        cell_format.set_align('center')
        cell_format2 = workbook.add_format()
        cell_format2.set_align('right')
        for i in range(len(headers)):
            sheet1.write(0, i, headers[i], cell_format)
        for row in range(self.tablaResultados.model().rowCount()):
            for column in range(self.tablaResultados.model().columnCount()):
                index = self.tablaResultados.model().index(row, column, parent)
                sheet1.write(row + 1, column, index.data(), cell_format2)
                sheet1.set_column(column, column, 20)
        # Guardar gráficos
        self.figure.savefig(self.imgdata, format="png")
        self.imgdata.seek(0)
        sheet2.insert_image(0, 0, "", {'image_data': self.imgdata})

    def click_finalizar(self):
        self.close()
Ejemplo n.º 36
0
class _QtDock(_AbstractDock):
    def _dock_initialize(self, window):
        self.dock = QDockWidget()
        self.scroll = QScrollArea(self.dock)
        self.dock.setWidget(self.scroll)
        widget = QWidget(self.scroll)
        self.scroll.setWidget(widget)
        self.scroll.setWidgetResizable(True)
        self.dock.setAllowedAreas(Qt.LeftDockWidgetArea)
        self.dock.setFeatures(QDockWidget.NoDockWidgetFeatures)
        window.addDockWidget(Qt.LeftDockWidgetArea, self.dock)
        self.dock_layout = QVBoxLayout()
        widget.setLayout(self.dock_layout)

    def _dock_finalize(self):
        self.dock.setMinimumSize(self.dock.sizeHint().width(), 0)
        self._dock_add_stretch(self.dock_layout)

    def _dock_show(self):
        self.dock.show()

    def _dock_hide(self):
        self.dock.hide()

    def _dock_add_stretch(self, layout):
        layout.addStretch()

    def _dock_add_layout(self, vertical=True):
        layout = QVBoxLayout() if vertical else QHBoxLayout()
        return layout

    def _dock_add_label(self, value, align=False, layout=None):
        layout = self.dock_layout if layout is None else layout
        widget = QLabel()
        if align:
            widget.setAlignment(Qt.AlignCenter)
        widget.setText(value)
        layout.addWidget(widget)
        return widget

    def _dock_add_button(self, name, callback, layout=None):
        layout = self.dock_layout if layout is None else layout
        # If we want one with text instead of an icon, we should use
        # QPushButton(name)
        widget = QToolButton()
        widget.clicked.connect(callback)
        widget.setText(name)
        layout.addWidget(widget)
        return widget

    def _dock_named_layout(self, name, layout, compact):
        layout = self.dock_layout if layout is None else layout
        if name is not None:
            hlayout = self._dock_add_layout(not compact)
            self._dock_add_label(value=name, align=not compact, layout=hlayout)
            layout.addLayout(hlayout)
            layout = hlayout
        return layout

    def _dock_add_slider(self,
                         name,
                         value,
                         rng,
                         callback,
                         compact=True,
                         double=False,
                         layout=None,
                         stretch=0):
        layout = self._dock_named_layout(name, layout, compact)
        slider_class = QFloatSlider if double else QSlider
        cast = float if double else int
        widget = slider_class(Qt.Horizontal)
        widget.setMinimum(cast(rng[0]))
        widget.setMaximum(cast(rng[1]))
        widget.setValue(cast(value))
        widget.valueChanged.connect(callback)
        layout.addWidget(widget)
        return widget

    def _dock_add_spin_box(self,
                           name,
                           value,
                           rng,
                           callback,
                           compact=True,
                           double=True,
                           layout=None):
        layout = self._dock_named_layout(name, layout, compact)
        value = value if double else int(value)
        widget = QDoubleSpinBox() if double else QSpinBox()
        widget.setAlignment(Qt.AlignCenter)
        widget.setMinimum(rng[0])
        widget.setMaximum(rng[1])
        inc = (rng[1] - rng[0]) / 20.
        inc = max(int(round(inc)), 1) if not double else inc
        widget.setKeyboardTracking(False)
        widget.setSingleStep(inc)
        widget.setValue(value)
        widget.valueChanged.connect(callback)
        layout.addWidget(widget)
        return widget

    def _dock_add_combo_box(self,
                            name,
                            value,
                            rng,
                            callback,
                            compact=True,
                            layout=None):
        layout = self._dock_named_layout(name, layout, compact)
        widget = QComboBox()
        widget.addItems(rng)
        widget.setCurrentText(value)
        widget.currentTextChanged.connect(callback)
        widget.setSizeAdjustPolicy(QComboBox.AdjustToContents)
        layout.addWidget(widget)
        return widget

    def _dock_add_group_box(self, name, layout=None):
        layout = self.dock_layout if layout is None else layout
        hlayout = QVBoxLayout()
        widget = QGroupBox(name)
        widget.setLayout(hlayout)
        layout.addWidget(widget)
        return hlayout
Ejemplo n.º 37
0
    def __init__(self, parent=None):
        super(ResultHandler, self).__init__()
        self.setWindowTitle('Dash results')
        self.control_label = QLabel()
        self.rendered_label = QLabel()
        self.diff_label = QLabel()

        self.mask_label = QLabel()
        self.new_mask_label = QLabel()

        self.scrollArea = QScrollArea()
        self.widget = QWidget()

        self.test_name_label = QLabel()
        grid = QGridLayout()
        grid.addWidget(self.test_name_label, 0, 0)
        grid.addWidget(QLabel('Control'), 1, 0)
        grid.addWidget(QLabel('Rendered'), 1, 1)
        grid.addWidget(QLabel('Difference'), 1, 2)
        grid.addWidget(self.control_label, 2, 0)
        grid.addWidget(self.rendered_label, 2, 1)
        grid.addWidget(self.diff_label, 2, 2)
        grid.addWidget(QLabel('Current Mask'), 3, 0)
        grid.addWidget(QLabel('New Mask'), 3, 1)
        grid.addWidget(self.mask_label, 4, 0)
        grid.addWidget(self.new_mask_label, 4, 1)

        self.widget.setLayout(grid)
        self.scrollArea.setWidget(self.widget)
        v_layout = QVBoxLayout()
        v_layout.addWidget(self.scrollArea, 1)

        next_image_button = QPushButton()
        next_image_button.setText('Skip')
        next_image_button.pressed.connect(self.load_next)

        self.overload_spin = QDoubleSpinBox()
        self.overload_spin.setMinimum(1)
        self.overload_spin.setMaximum(255)
        self.overload_spin.setValue(1)
        self.overload_spin.valueChanged.connect(
            lambda: save_mask_button.setEnabled(False))

        preview_mask_button = QPushButton()
        preview_mask_button.setText('Preview New Mask')
        preview_mask_button.pressed.connect(self.preview_mask)
        preview_mask_button.pressed.connect(
            lambda: save_mask_button.setEnabled(True))

        save_mask_button = QPushButton()
        save_mask_button.setText('Save New Mask')
        save_mask_button.pressed.connect(self.save_mask)

        button_layout = QHBoxLayout()
        button_layout.addWidget(next_image_button)
        button_layout.addWidget(QLabel('Mask diff multiplier:'))
        button_layout.addWidget(self.overload_spin)
        button_layout.addWidget(preview_mask_button)
        button_layout.addWidget(save_mask_button)
        button_layout.addStretch()
        v_layout.addLayout(button_layout)
        self.setLayout(v_layout)
Ejemplo n.º 38
0
class CatalogMainWindow(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)

        # Структура главного окна
        # Создаем меню
        self.menu_bar = self.menuBar()

        # Создаем блоки меню
        # Блок меню 'Учет движения товаров'

        self.gma_menu = self.menu_bar.addMenu('Учет движения товаров')
        self.gma_menu.setEnabled(False)
        self.ro_open_btn = QAction(self)
        self.ro_open_btn.setText('Приходный ордер')
        self.wo_open_btn = QAction(self)
        self.wo_open_btn.setText('Расходный ордер')
        self.gma_menu.addAction(self.ro_open_btn)
        self.gma_menu.addAction(self.wo_open_btn)

        # Блок меню 'Отчеты'

        self.r_menu = self.menu_bar.addMenu('Отчеты')
        self.r_menu.setEnabled(False)
        self.tws_report_btn = QAction(self)
        self.tws_report_btn.setText('Операции с поставщиками')
        self.gis_report_btn = QAction(self)
        self.gis_report_btn.setText('Товары в наличии')
        self.r_menu.addAction(self.tws_report_btn)
        self.r_menu.addAction(self.gis_report_btn)

        # Блок меню 'Справочники'
        self.d_menu = self.menu_bar.addMenu('Справочники')
        self.d_menu.setEnabled(False)

        self.u_catalog_btn = QAction(self)
        self.u_catalog_btn.setText('Пользователи')

        self.r_catalog_btn = QAction(self)
        self.r_catalog_btn.setText('Права пользователей')

        self.c_catalog_btn = QAction(self)
        self.c_catalog_btn.setText('Категории')

        self.n_catalog_btn = QAction(self)
        self.n_catalog_btn.setText('Номенклатура товаров')

        self.un_catalog_btn = QAction(self)
        self.un_catalog_btn.setText('Единицы измерения')

        self.s_catalog_btn = QAction(self)
        self.s_catalog_btn.setText('Поставщики')

        self.p_catalog_btn = QAction(self)
        self.p_catalog_btn.setText('Должности')

        self.e_catalog_btn = QAction(self)
        self.e_catalog_btn.setText('Сотрудники')

        self.d_menu.addAction(self.u_catalog_btn)
        self.d_menu.addAction(self.r_catalog_btn)
        self.d_menu.addAction(self.c_catalog_btn)
        self.d_menu.addAction(self.n_catalog_btn)
        self.d_menu.addAction(self.un_catalog_btn)
        self.d_menu.addAction(self.s_catalog_btn)
        self.d_menu.addAction(self.p_catalog_btn)
        self.d_menu.addAction(self.e_catalog_btn)

        # Верхний виджет с полным путем до файла БД

        self.db_lbl = QLabel()
        self.db_lbl.setText('Путь до БД:')
        self.db_lbl.setStyleSheet("border-style: none;" "font-size: 10pt;")
        self.db_path_lbl = QLineEdit()
        self.db_path_lbl.setStyleSheet(
            "background-color: white;"
            "font-size: 10pt;"
            "color: green;")
        self.db_path_lbl.setFixedSize(700, 25)
        self.db_path_lbl.setEnabled(False)
        self.db_path_btn = QPushButton('...')
        self.db_path_btn.setFixedSize(25, 25)
        self.db_path_btn.setStyleSheet(
            "border-width: 1px;"
            "border-style: solid;"
            "border-color: dimgray;"
            "border-radius: 5px;"
            "background-color: gainsboro;")
        self.db_path_btn.clicked.connect(self.on_db_path_btn_clicked)

        self.tdw = QDockWidget()
        self.tdw.setFixedHeight(65)
        self.tdw.setFeatures(self.tdw.NoDockWidgetFeatures)
        self.tdw_grid = QGridLayout()
        self.tdw_grid.setColumnStretch(3, 1)
        self.tdw_grid.addWidget(self.db_lbl)
        self.tdw_grid.addWidget(self.db_path_lbl)
        self.tdw_grid.addWidget(self.db_path_btn)
        self.tdw_frame = QFrame()
        self.tdw_frame.setStyleSheet(
            "background-color: ghostwhite;"
            "border-width: 0.5px;"
            "border-style: solid;"
            "border-color: silver;")
        self.tdw_frame.setLayout(self.tdw_grid)
        self.tdw.setWidget(self.tdw_frame)
        self.addDockWidget(QtCore.Qt.TopDockWidgetArea, self.tdw)

        # Левый виджет с окном каталога продукции

        self.ldw = QDockWidget()
        self.ldw.setFixedSize(500, 570)
        self.ldw.setFeatures(self.ldw.NoDockWidgetFeatures)
        self.ldw_tree = QTreeView()
        self.ldw_tree.setFixedSize(500, 530)
        self.ldw_tree.setHeaderHidden(True)
        self.ldw_tree_model = QStandardItemModel()
        self.ldw_tree.setModel(self.ldw_tree_model)
        self.ldw_tree.clicked.connect(self.on_ldw_tree_clicked)
        self.outf_scroll = QScrollArea()
        self.outf_scroll.setWidget(self.ldw_tree)
        self.ldw.setWidget(self.outf_scroll)
        self.ldw.setWindowTitle("Каталог продукции")

        # Центральный виджет с карточкой товара

        self.cdw = QDockWidget()
        self.cdw.setFeatures(self.cdw.NoDockWidgetFeatures)
        #self.setCentralWidget(self.cdw)

        # Нижний виджет со служебными сообщениями

        self.smdw = QDockWidget()
        self.smdw.setFixedHeight(140)
        self.smdw.setFeatures(self.smdw.NoDockWidgetFeatures)
        self.sm_list_widget = QListWidget()
        self.smdw.setWidget(self.sm_list_widget)
        self.smdw.setWindowTitle("Служебные сообщения")

    # Функции главного окна
    # Функция выбора файла базы данных
    def on_db_path_btn_clicked(self):
        global db_path
        db_path, _filter = QFileDialog.getOpenFileName(
            None, "Open Data File", '.', "(*.sqlite)")
        self.db_path_lbl.setText(db_path)
        self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.ldw)
        self.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.smdw)

        # Создаем все таблицы, которые нужны
        con = QtSql.QSqlDatabase.addDatabase('QSQLITE')
        con.setDatabaseName(db_path)
        con.open()

        if 'rules' not in con.tables():

            query = QtSql.QSqlQuery()
            query.exec(
                "CREATE TABLE rules(rule STRING UNIQUE, description STRING)")

            r1 = "admin"
            d1 = "Доступны все опции"
            query.exec(
                "INSERT INTO rules(rule, description) VALUES ('%s','%s')" %
                (r1, d1))

            r2 = "Кладовщик"
            d2 = "Доступны опции кладовщика"
            query.exec(
                "INSERT INTO rules(rule, description) VALUES ('%s','%s')" %
                (r2, d2))

        if 'nomenclature' not in con.tables():
            query = QtSql.QSqlQuery()
            query.exec(
                "CREATE TABLE nomenclature(item_numb INTEGER UNIQUE PRIMARY KEY NOT NULL, \
                item_name STRING NOT NULL, item_unit STRING REFERENCES units (unit) NOT NULL, \
                item_cat STRING REFERENCES categories (category) NOT NULL, item_img BLOB)")

        if 'units' not in con.tables():
            query = QtSql.QSqlQuery()
            query.exec("CREATE TABLE units(unit STRING PRIMARY KEY \
            UNIQUE NOT NULL)")

        if 'categories' not in con.tables():
            query = QtSql.QSqlQuery()
            query.exec(
                "CREATE TABLE categories(category STRING PRIMARY KEY UNIQUE \
                NOT NULL, description STRING NOT NULL)")

        # Создаем таблицу 'users', если не существует
        if 'users' not in con.tables():
            query = QtSql.QSqlQuery()
            query.exec(
                "CREATE TABLE users(id_user INTEGER PRIMARY KEY AUTOINCREMENT \
                unique NOT NULL, \
                login STRING UNIQUE NOT NULL, password STRING NOT NULL, \
                name TEXT NOT NULL, \
                rules STRING REFERENCES rules (rule) NOT NULL)")

        if 'suppliers' not in con.tables():
            query = QtSql.QSqlQuery()
            query.exec("CREATE TABLE suppliers( \
                id_supplier INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT NOT NULL, \
                supplier STRING UNIQUE NOT NULL, \
                ownerchipform STRING NOT NULL, \
                address STRING NOT NULL, \
                phone STRING NOT NULL, \
                email STRING NOT NULL \
            )")

        if 'positions' not in con.tables():
            query = QtSql.QSqlQuery()
            query.exec(
                "CREATE TABLE positions(position STRING PRIMARY KEY UNIQUE \
                NOT NULL)")

        if 'employee' not in con.tables():
            query = QtSql.QSqlQuery()
            query.exec(
                "CREATE TABLE employee(employee_id INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT, \
                fio STRING NOT NULL, \
                position STRING REFERENCES positions (position) NOT NULL)")

        con.close()



        con = sqlite3.connect(db_path)
        cur = con.cursor()
        sql_cats_select = """\
        SELECT DISTINCT item_cat FROM nomenclature
        """
        cur.execute(sql_cats_select)
        arr = cur.fetchall()
        #print(arr)

        for cat in arr:
            sql_items_select = "SELECT item_name FROM nomenclature \
            WHERE item_cat = ?"
            cur.execute(sql_items_select, [cat[0]])
            items = cur.fetchall()
            #print(items)
            parent_item = QStandardItem(cat[0])
            self.ldw_tree_model.appendRow(parent_item)

            j = 0

            for item in items:
                child_item = QStandardItem(item[0])
                parent_item.setChild(j, 0, child_item)
                j = j + 1


        cur.close()
        con.close()

        self.gma_menu.setEnabled(True)
        self.r_menu.setEnabled(True)
        self.d_menu.setEnabled(True)

        self.ro_open_btn.triggered.connect(
            lambda: documents_class.on_ro_doc_btn(
                self, db_path))
        self.wo_open_btn.triggered.connect(
            lambda: documents_class.on_wo_doc_btn(
                self, db_path))

        self.gis_report_btn.triggered.connect(
            lambda: gis_report_class.on_gis_report_btn(
                self, db_path))

        self.tws_report_btn.triggered.connect(
            lambda: tws_report_class.on_tws_report_btn(
                self, db_path))

        self.u_catalog_btn.triggered.connect(
            lambda: directories_class.on_u_catalog_btn(
                self, db_path))
        self.r_catalog_btn.triggered.connect(
            lambda: directories_class.on_r_catalog_btn(
                self, db_path))
        self.c_catalog_btn.triggered.connect(
            lambda: directories_class.on_c_catalog_btn(
                self, db_path))
        self.n_catalog_btn.triggered.connect(
            lambda: directories_class.on_n_catalog_btn(
                self, db_path))
        self.un_catalog_btn.triggered.connect(
            lambda: directories_class.on_un_catalog_btn(
                self, db_path))
        self.s_catalog_btn.triggered.connect(
            lambda: directories_class.on_s_catalog_btn(
                self, db_path))
        self.p_catalog_btn.triggered.connect(
            lambda: directories_class.on_p_catalog_btn(
                self, db_path))
        self.e_catalog_btn.triggered.connect(
            lambda: directories_class.on_e_catalog_btn(
                self, db_path))

    # Функция выбора товара из каталога-дерева
    def on_ldw_tree_clicked(self):
        #print('вах')


        try:
            current_index = self.ldw_tree.currentIndex()
            file_name = self.ldw_tree.model().data(current_index)
            con = sqlite3.connect(db_path)
            cur = con.cursor()
            sql_item_select = "SELECT item_name FROM nomenclature \
            WHERE item_name = ?"
            cur.execute(sql_item_select, [file_name])
            item = cur.fetchone()
            if item:
                self.setCentralWidget(self.cdw)
                self.cdw.setWindowTitle("Карточка товара")
                item_card = item_card_class(self, db_path, file_name)
                self.cdw.setWidget(item_card)
            cur.close()
            con.close()
        except Exception as e:
            print('Ошибка:\n', traceback.format_exc())
Ejemplo n.º 39
0
    def __init__(self):

        self.analysisManager = AnalysisXmlManager()

        super().__init__()
        stringsPOI = []
        functionsPOI = []
        variablesPOI = []
        protocolsPOI = []
        structuresPOI = []
        poiSuperList = []
        self.BeatTree = ET.parse('../xml/Beat.xml')
        self.BeatRoot = self.BeatTree.getroot()
        self.poiSuperList2 = []
        mainlayout = QGridLayout()
        leftLayout = QGridLayout()
        rightLayout = QGridLayout()
        self.topLayout = QGridLayout()
        mainlayout.addLayout(self.topLayout, 0, 0, 1, 6)
        mainlayout.addLayout(leftLayout, 1, 0, 6, 1)
        mainlayout.addLayout(rightLayout, 1, 1, 6, 5)
        self.static_analysis_label = QLabel('Dynamic Analysis ')

        # Top layout elements
        self.pluginDropdown = QComboBox()
        self.runStatic = QPushButton('Run')
        self.poiDropdown = QComboBox()
        self.runDynamic = QPushButton('Run')
        self.stopDynamic = QPushButton('Stop')

        self.topLayout.addWidget(QLabel('Plugin'), 0, 0)
        self.topLayout.addWidget(self.pluginDropdown, 0, 1, 1, 2)
        self.topLayout.addWidget(QLabel('Static Analysis'), 1, 0)
        self.topLayout.addWidget(self.runStatic, 1, 1, 1, 1)
        self.topLayout.addWidget(QLabel('Point of Interest Type'), 2, 0)
        self.topLayout.addWidget(self.poiDropdown, 2, 1, 1, 2)
        self.topLayout.addWidget(self.static_analysis_label, 1, 5, 1, 1)
        self.topLayout.addWidget(self.runDynamic, 1, 6)
        self.topLayout.addWidget(self.stopDynamic, 1, 7)
        self.topLayout.addWidget(QLabel(), 0, 3, 1, 15)

        # Left panel
        self.searchBox = QLineEdit()
        self.searchButton = QPushButton('Search')
        self.searchedWord = []

        self.poiList = QListWidget()
        leftPanelLabel = QLabel('Point of Interest View')
        leftPanelLabel.setFont(
            QtGui.QFont('Arial', 12, weight=QtGui.QFont().Bold))
        leftPanelLabel.setAlignment(Qt.AlignCenter)

        leftLayout.addWidget(leftPanelLabel, 0, 0, 1, 4)
        leftLayout.addWidget(self.searchBox, 1, 0, 1, 3)
        leftLayout.addWidget(self.searchButton, 1, 3, 1, 1)
        leftLayout.addWidget(self.poiList, 2, 0, 1, 4)

        # Right panel
        rightPanelLabel = QLabel('Point of Interest View')
        rightPanelLabel.setFont(
            QtGui.QFont('Arial', 12, weight=QtGui.QFont().Bold))
        rightPanelLabel.setAlignment(Qt.AlignCenter)
        self.poiContentArea = QScrollArea()
        self.terminal = QTextEdit()
        self.commentButton = QPushButton('Comments')
        self.current_project = QLabel('Current Project: ')

        rightLayout.addWidget(rightPanelLabel, 0, 0, 1, 10)
        rightLayout.addWidget(self.poiContentArea, 1, 0, 10, 8)
        rightLayout.addWidget(self.terminal, 11, 0, 10, 8)
        rightLayout.addWidget(self.commentButton, 2, 8)

        # Functionality
        self.commentButton.clicked.connect(self.openCommentWindow)

        # set Plugin name
        self.pluginDropdown.addItem("Select Plugin")
        self.pluginDropdown.activated[str].connect(self.onActivated)

        self.poiDropdown.activated[str].connect(self.displayPOI)
        self.runStatic.clicked.connect(self.clickStaticAnalysis)
        self.searchButton.clicked.connect(self.clickedSearch)
        self.poiList.clicked.connect(self.expandPOI)
        self.setLayout(mainlayout)

        # this should not be visible at start
        self.runDynamic.hide()
        self.stopDynamic.hide()
        self.static_analysis_label.hide()
        self.displayCurrentProject("No Project Selected", "")

        self.setLayout(mainlayout)
        self.populatePluginDropdown()
Ejemplo n.º 40
0
class AnalysisTab(QWidget):
    def __init__(self):

        self.analysisManager = AnalysisXmlManager()

        super().__init__()
        stringsPOI = []
        functionsPOI = []
        variablesPOI = []
        protocolsPOI = []
        structuresPOI = []
        poiSuperList = []
        self.BeatTree = ET.parse('../xml/Beat.xml')
        self.BeatRoot = self.BeatTree.getroot()
        self.poiSuperList2 = []
        mainlayout = QGridLayout()
        leftLayout = QGridLayout()
        rightLayout = QGridLayout()
        self.topLayout = QGridLayout()
        mainlayout.addLayout(self.topLayout, 0, 0, 1, 6)
        mainlayout.addLayout(leftLayout, 1, 0, 6, 1)
        mainlayout.addLayout(rightLayout, 1, 1, 6, 5)
        self.static_analysis_label = QLabel('Dynamic Analysis ')

        # Top layout elements
        self.pluginDropdown = QComboBox()
        self.runStatic = QPushButton('Run')
        self.poiDropdown = QComboBox()
        self.runDynamic = QPushButton('Run')
        self.stopDynamic = QPushButton('Stop')

        self.topLayout.addWidget(QLabel('Plugin'), 0, 0)
        self.topLayout.addWidget(self.pluginDropdown, 0, 1, 1, 2)
        self.topLayout.addWidget(QLabel('Static Analysis'), 1, 0)
        self.topLayout.addWidget(self.runStatic, 1, 1, 1, 1)
        self.topLayout.addWidget(QLabel('Point of Interest Type'), 2, 0)
        self.topLayout.addWidget(self.poiDropdown, 2, 1, 1, 2)
        self.topLayout.addWidget(self.static_analysis_label, 1, 5, 1, 1)
        self.topLayout.addWidget(self.runDynamic, 1, 6)
        self.topLayout.addWidget(self.stopDynamic, 1, 7)
        self.topLayout.addWidget(QLabel(), 0, 3, 1, 15)

        # Left panel
        self.searchBox = QLineEdit()
        self.searchButton = QPushButton('Search')
        self.searchedWord = []

        self.poiList = QListWidget()
        leftPanelLabel = QLabel('Point of Interest View')
        leftPanelLabel.setFont(
            QtGui.QFont('Arial', 12, weight=QtGui.QFont().Bold))
        leftPanelLabel.setAlignment(Qt.AlignCenter)

        leftLayout.addWidget(leftPanelLabel, 0, 0, 1, 4)
        leftLayout.addWidget(self.searchBox, 1, 0, 1, 3)
        leftLayout.addWidget(self.searchButton, 1, 3, 1, 1)
        leftLayout.addWidget(self.poiList, 2, 0, 1, 4)

        # Right panel
        rightPanelLabel = QLabel('Point of Interest View')
        rightPanelLabel.setFont(
            QtGui.QFont('Arial', 12, weight=QtGui.QFont().Bold))
        rightPanelLabel.setAlignment(Qt.AlignCenter)
        self.poiContentArea = QScrollArea()
        self.terminal = QTextEdit()
        self.commentButton = QPushButton('Comments')
        self.current_project = QLabel('Current Project: ')

        rightLayout.addWidget(rightPanelLabel, 0, 0, 1, 10)
        rightLayout.addWidget(self.poiContentArea, 1, 0, 10, 8)
        rightLayout.addWidget(self.terminal, 11, 0, 10, 8)
        rightLayout.addWidget(self.commentButton, 2, 8)

        # Functionality
        self.commentButton.clicked.connect(self.openCommentWindow)

        # set Plugin name
        self.pluginDropdown.addItem("Select Plugin")
        self.pluginDropdown.activated[str].connect(self.onActivated)

        self.poiDropdown.activated[str].connect(self.displayPOI)
        self.runStatic.clicked.connect(self.clickStaticAnalysis)
        self.searchButton.clicked.connect(self.clickedSearch)
        self.poiList.clicked.connect(self.expandPOI)
        self.setLayout(mainlayout)

        # this should not be visible at start
        self.runDynamic.hide()
        self.stopDynamic.hide()
        self.static_analysis_label.hide()
        self.displayCurrentProject("No Project Selected", "")

        self.setLayout(mainlayout)
        self.populatePluginDropdown()

    def populatePluginDropdown(self):
        pluginList = self.analysisManager.getListOfPluginsForAnalysis()
        for plugin in pluginList:
            self.pluginDropdown.addItem(plugin)

    def displayCurrentProject(self, project_name, project_path):
        self.current_project.clear()
        self.topLayout.addWidget(self.current_project, 0, 20)
        current = 'Current Project:  ' + project_name + '\n' + 'Binary File: ' + project_path
        self.current_project = QLabel(current)
        self.topLayout.addWidget(self.current_project, 0, 20)

    def clickedSearch(self):
        global poiSuperList
        target = self.searchBox.text()
        self.searchedWord = [s for s in poiSuperList if target in s]
        self.poiList.clear()
        for items in self.searchedWord:
            self.poiList.addItem(items)

    def displayPOIparam(self):
        content_widget = QWidget()
        self.poiContentArea.setWidget(content_widget)
        layoutForPOI = QGridLayout(content_widget)
        self.poiContentArea.setWidgetResizable(True)
        option = self.poiDropdown.currentText()
        if option == "Strings":
            for i in range(layoutForPOI.count()):
                layoutForPOI.itemAt(i).widget().close()
            value = QLabel('Value:')
            sectionInBinary = QLabel('Section In Binary:')
            self.valueLine = QLineEdit()
            self.sectionInBinaryLine = QLineEdit()
            layoutForPOI.addWidget(value, 1, 0)
            layoutForPOI.addWidget(self.valueLine, 1, 1)
            layoutForPOI.addWidget(sectionInBinary, 2, 0)
            layoutForPOI.addWidget(self.sectionInBinaryLine, 2, 1)
        elif option == "Functions":
            for i in range(layoutForPOI.count()):
                layoutForPOI.itemAt(i).widget().close()

            order = QLabel('Order of Parameters:')
            fpType = QLabel('Parameter Type:')
            fpValue = QLabel('Parameter Value:')
            frType = QLabel('Return Type:')
            frValue = QLabel('Return Value:')
            fRelativeOrder = QLabel('Order in Relation to :')

            self.orderLine = QLineEdit()
            self.fpTypeLine = QLineEdit()
            self.fpValueLine = QLineEdit()
            self.frValueLine = QLineEdit()
            self.frTypeLine = QLineEdit()
            self.fRelativeOrderLine = QLineEdit()

            layoutForPOI.addWidget(order, 1, 0)
            layoutForPOI.addWidget(self.orderLine, 1, 1)
            layoutForPOI.addWidget(fpType, 2, 0)
            layoutForPOI.addWidget(self.fpTypeLine, 2, 1)
            layoutForPOI.addWidget(frValue, 3, 0)
            layoutForPOI.addWidget(self.frValueLine, 3, 1)
            layoutForPOI.addWidget(fRelativeOrder, 4, 0)
            layoutForPOI.addWidget(self.fRelativeOrderLine, 4, 1)

        elif option == "Variables":
            for i in range(layoutForPOI.count()):
                layoutForPOI.itemAt(i).widget().close()
            variableType = QLabel('Variable Type:')
            value = QLabel('Value:')
            sectionInBinary = QLabel('Section In Binary:')
            variableTypeLine = QLineEdit()
            valueLine = QLineEdit()
            sectionInBinaryLine = QLineEdit()
            layoutForPOI.addWidget(variableType, 1, 0)
            layoutForPOI.addWidget(variableTypeLine, 1, 1)
            layoutForPOI.addWidget(value, 2, 0)
            layoutForPOI.addWidget(valueLine, 2, 1)
            layoutForPOI.addWidget(sectionInBinary, 3, 0)
            layoutForPOI.addWidget(sectionInBinaryLine, 3, 1)
        elif option == "Structures":
            for i in range(layoutForPOI.count()):
                layoutForPOI.itemAt(i).widget().close()
            memberOrder = QLabel('Member Order:')
            memberType = QLabel('Value:')
            sectionInBinary = QLabel('Section In Binary:')
            memberValue = QLabel('Member Value:')
            memberOrderLine = QLineEdit()
            memberTypeLine = QLineEdit()
            sectionInBinaryLine = QLineEdit()
            memberValueLine = QLineEdit()
            layoutForPOI.addWidget(sectionInBinary, 1, 0)
            layoutForPOI.addWidget(sectionInBinaryLine, 1, 1)
            layoutForPOI.addWidget(memberOrder, 2, 0)
            layoutForPOI.addWidget(memberOrderLine, 2, 1)
            layoutForPOI.addWidget(memberType, 3, 0)
            layoutForPOI.addWidget(memberTypeLine, 3, 1)
            layoutForPOI.addWidget(memberValue, 4, 0)
            layoutForPOI.addWidget(memberValueLine, 4, 1)
        elif option == "Protocols":
            for i in range(layoutForPOI.count()):
                layoutForPOI.itemAt(i).widget().close()
            pStructure = QLabel('Structure')
            pSize = QLabel('Size')
            sectionInBinary = QLabel('Section In Binary:')
            pSizeLine = QLineEdit()
            pStructureLine = QLineEdit()
            sectionInBinaryLine = QLineEdit()
            layoutForPOI.addWidget(sectionInBinary, 1, 0)
            layoutForPOI.addWidget(sectionInBinaryLine, 1, 1)
            layoutForPOI.addWidget(pStructure, 2, 0)
            layoutForPOI.addWidget(pStructureLine, 2, 1)
            layoutForPOI.addWidget(pSize, 3, 0)
            layoutForPOI.addWidget(pSizeLine, 3, 1)
        else:
            for i in range(layoutForPOI.count()):
                layoutForPOI.itemAt(i).widget().close()

    def parseNetworkItems(self):
        global poiSuperList
        target = ['socket', 'send', 'rec', 'ipv', 'main']
        for i in target:
            self.searchedWord.append([s for s in poiSuperList if i in s])

        self.poiList.clear()
        poiSuperList = []
        for items in self.searchedWord:
            for item2 in items:
                self.poiList.addItem(item2)
        self.searchedWord = []

    def expandPOI(self):
        dataSet = self.analysisManager.getAnalysis()
        pois = dataSet[1]
        option = self.poiDropdown.currentText()

        if option == 'Strings':
            currentItem = self.poiList.currentItem().text()
            strings = pois['Project']['StaticAnalysis'][
                'stringPointOfInterest']
            for i in range(
                    len(strings)):  # access each individual function POI
                poi = strings[i]
                if currentItem == poi['value']:
                    self.valueLine.setText(poi['address'])
                    self.sectionInBinaryLine.setText(poi['section'])

        if option == 'Functions':
            currentItem = self.poiList.currentItem().text()
            functions = pois['Project']['StaticAnalysis'][
                'functionPointOfInterest']
            for i in range(
                    len(functions)):  # access each individual function POI
                poi = functions[i]
                if currentItem == poi['name']:
                    self.orderLine.setText(poi['name'])
                    self.fpTypeLine.setText(poi['parameterType'])
                    self.frValueLine.setText(poi['address'])
                    self.fRelativeOrderLine.setText(
                        poi['breakpoints']['breakpoint'])

    def displayPOI(self, option):
        dataSet = self.analysisManager.getAnalysis()
        pois = dataSet[1]

        if option == "Strings":
            self.poiList.clear()
            strings = pois['Project']['StaticAnalysis'][
                'stringPointOfInterest']
            for i in range(len(strings)):
                self.poiList.addItem(strings[i]['value'])

        if option == "Functions":
            self.poiList.clear()
            functions = pois['Project']['StaticAnalysis'][
                'functionPointOfInterest']
            for i in range(len(functions)):
                self.poiList.addItem(functions[i]['name'])
        self.displayPOIparam()

    def onActivated(self, option):
        # make invisible
        self.runDynamic.hide()
        self.stopDynamic.hide()
        self.static_analysis_label.hide()

        data = []
        BeatTree = ET.parse("../xml/Beat.xml")
        root = BeatTree.getroot()
        pluginData = root.find('./Plugins/Plugin/DataInPlugin')
        pluginName = root.findall('./Plugins/Plugin/Plugin_name')
        self.poiDropdown.clear()
        self.poiDropdown.addItem("Select POI to display")
        self.poiDropdown.addItem("Display All for {}".format(option))
        for item in pluginName:
            data.append(item.text)
            if item.text == option:
                pluginData = root.find(
                    './Plugins/Plugin[@nameOfPlugin="{}"]/DataInPlugin'.format(
                        option))
                for element in pluginData:
                    plugin = element.get('name')
                    self.poiDropdown.addItem(plugin)

    def makeStringTree(self, stringsData, parentRoot):
        poiHolderElement = parentRoot.find('./StaticAnalysis')

        for index in range(len(stringsData)):  # access each string
            myString = stringsData[
                index]  # this dictionary contains one String POI
            tree = ET.parse('../xml/StringPointOfInterest.xml')
            root = tree.getroot()
            b2tf = root.find("./value")
            b2tf.text = str(base64.standard_b64decode(myString['string']))
            b2tf = root.find("./address")
            b2tf.text = str(hex(myString['vaddr']))
            b2tf = root.find("./section")
            b2tf.text = str(myString['section'])
            poiHolderElement.append(root)

    def makeFunctionsTree(self, functionsData, parentRoot, r2buffer):
        poiHolderElement = parentRoot.find('./StaticAnalysis')
        r2buffer.cmd(
            'doo'
        )  # need to open file in debug mode to find references for breakpoints

        for index in range(len(functionsData)):  # access each function
            myFunction = functionsData[
                index]  # this dictionary contains one function POI
            tree = ET.parse('../xml/FunctionPointOfInterest.xml')
            root = tree.getroot()
            b2tf = root.find("./name")
            b2tf.text = str(myFunction['name'])
            b2tf = root.find("./address")
            b2tf.text = str(hex(myFunction['offset']))
            b2tf = root.find("./parameterType")

            breakpoints = []  # this will hold a list of our breakpoints
            breakpointElement = root.find('./breakpoints')
            jsonReferences = json.loads(
                r2buffer.cmd('axtj ' + myFunction['name']))
            breakpoints.clear()

            for i in range(len(jsonReferences)):
                breakpoints.append(str(hex(jsonReferences[i]['from'])))
            for bp in breakpoints:
                tempElement = ET.SubElement(breakpointElement, 'breakpoint')
                tempElement.text = bp
            poiHolderElement.append(root)

    def clickStaticAnalysis(self):
        global stringsPOI
        global variablesPOI
        global functionsPOI
        global protocolsPOI
        global structuresPOI

        global parentRoot  # holds all POIs from static analysis

        self.poiList.clear()
        self.terminal.setText("Running Static Analysis..")
        project_name = pt.project['Project']['Project_name']['#text']
        project_path = pt.project['Project']['BinaryFilePath']['#text']
        self.displayCurrentProject(project_name, project_path)

        bina = r2pipe.open(pt.project['Project']['BinaryFilePath']['#text'])
        bina.cmd("aaa")  # analyze binary in Radare2

        # extracting POI data from Radare2 and storing as json dictionaries
        stringsPOI = bina.cmd("izj")
        jsonStrings = json.loads(stringsPOI)
        functionsPOI = bina.cmd("aflj")
        jsonFunctions = json.loads(functionsPOI)

        # get handle to Project xml, create POI xmls, and upload them to DB
        parentTree = ET.parse('../xml/Project.xml')

        parentRoot = parentTree.getroot()
        parentRootName = parentRoot.find('./Project_name')
        parentRootName.text = project_name

        self.makeStringTree(jsonStrings, parentRoot)
        self.makeFunctionsTree(jsonFunctions, parentRoot, bina)
        parent_dict = ET.tostring(parentRoot, encoding='utf8').decode('utf8')
        self.analysisManager.uploadAnalysis(parent_dict)

        self.terminal.append("Static Analysis done!")

        # Make dynamic visible here
        self.runDynamic.show()
        self.stopDynamic.show()
        self.static_analysis_label.show()

    # Methods to open windows
    def openCommentWindow(self):
        self.window = QtWidgets.QDialog()
        self.ui = comment_window()
        self.ui.setupUi(self.window)
        self.window.show()

    def openAnalysisWindow(self):
        self.window = QtWidgets.QDialog()
        self.ui = analysis_window()
        self.ui.setupUi(self.window)
        self.window.show()

    def openOutputWindow(self):
        self.window = QtWidgets.QDialog()
        self.ui = output_Field_Window()
        self.ui.setupUi(self.window)
        self.window.show()
Ejemplo n.º 41
0
class PreferencesDialog(QDialog):

    fft_check_signal = pyqtSignal()
    fft_check_result = 0

    def __init__(self, preferences):
        super(PreferencesDialog, self).__init__()
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setWindowTitle
        self.title = 'Additional Preferences | ' + __appname__ + 'v' + __version__
        self.setWindowTitle(self.title)
        self.resize(500, 500)

        self.outer_layout = QVBoxLayout()
        self.outer_layout.setContentsMargins(5, 3, 5, 7)
        self.outer_layout.setSpacing(10)

        self.pref_widget = QWidget()
        self.vlayout = QVBoxLayout()
        self.vlayout.setContentsMargins(5, 3, 5, 7)
        self.vlayout.setSpacing(10)

        self.app_settings_gb = AppSettingsGroupBox(preferences)
        self.data_settings_gb = DataSettingsGroupBox(preferences)
        self.ref_proc_settings_gb = IterativeProcedureSettingsGroupBox(
            preferences)
        self.refine_settings_gb = SolverSettingsGroupBox(preferences)
        self.global_min_settings_gb = GlobalMinSettingsGroupBox(preferences)
        self.gaussian_fit_settings_gb = GaussianFittingSettingsGroupBox(
            preferences)

        self.vlayout.addWidget(self.app_settings_gb)
        self.vlayout.addWidget(self.data_settings_gb)
        self.vlayout.addWidget(self.ref_proc_settings_gb)
        self.vlayout.addWidget(self.refine_settings_gb)
        self.vlayout.addWidget(self.global_min_settings_gb)
        self.vlayout.addWidget(self.gaussian_fit_settings_gb)
        self.pref_widget.setLayout(self.vlayout)

        self.scroll_area = QScrollArea()
        self.scroll_area.setFrameShape(QFrame.NoFrame)
        self.scroll_area.setWidget(self.pref_widget)
        self.scroll_area.setWidgetResizable(True)

        self.button_box = QDialogButtonBox()
        self.button_box.addButton('&Cancel', QDialogButtonBox.RejectRole)
        self.button_box.addButton('&Apply', QDialogButtonBox.AcceptRole)

        self.hline = QFrame()
        self.hline.setFrameShape(QFrame.HLine)
        self.hline.setFrameShadow(QFrame.Sunken)
        self.hline.setObjectName('hline')

        self.outer_layout.addWidget(self.scroll_area)
        self.outer_layout.addWidget(self.hline)
        self.outer_layout.addWidget(self.button_box)

        self.setLayout(self.outer_layout)

        self.button_box.accepted.connect(self.accept_preferences)
        self.button_box.rejected.connect(self.rejected)

        self.rejected.connect(self.close)

    def accept_preferences(self):

        # Log mode
        if self.app_settings_gb.log_mode_input.currentText() == 'Append':
            _append_log_mode = 1
        else:
            _append_log_mode = 0

        try:
            _data_units = np.int(
                self.data_settings_gb.data_units_input.currentIndex())
            _window_length = np.int(
                self.data_settings_gb.window_length_input.text())
            _poly_order = np.int(self.data_settings_gb.poly_order_input.text())
            _rescale_AL = np.int(
                self.data_settings_gb.rescale_AL_input.isChecked())
            _fft_N = np.int(self.data_settings_gb.fft_N_input.value())
            self.fft_check = _fft_N
            self.fft_check_signal.emit()
            if self.fft_check_result == 1:
                raise RuntimeWarning()
            _mod_func_mode = np.int(
                self.ref_proc_settings_gb.mod_func_mode_input.isChecked())
            _op_method = self.refine_settings_gb.op_method_input.currentText()
            _disp = np.int(self.refine_settings_gb.disp_check.isChecked())
            _maxiter = np.int(self.refine_settings_gb.maxiter_input.text())
            _ftol = np.float(self.refine_settings_gb.ftol_input.text())
            # Get l_bfgs_b specific options
            if _op_method == 'L-BFGS-B':
                _maxfun = np.int(self.refine_settings_gb.maxfun_input.text())
                _gtol = np.float(self.refine_settings_gb.gtol_input.text())
            # Get globam minimisation (basin-hopping) options
            _bh_disp = np.int(
                self.global_min_settings_gb.disp_check.isChecked())
            _bh_niter = np.int(
                self.global_min_settings_gb.niter_basin_input.text())
            _bh_temp = np.float(
                self.global_min_settings_gb.temp_basin_input.text())
            _bh_step_size = np.float(
                self.global_min_settings_gb.stepsize_basin_input.text())
            _bh_interval = np.int(
                self.global_min_settings_gb.interval_basin_input.text())
            # Get Gaussiant fitting options
            _xray_weight_mode = np.int(self.gaussian_fit_settings_gb.
                                       xray_weight_mode_input.isChecked())

        # Handle for missing values
        except ValueError:
            _message = [
                'Missing Values!', 'Please ensures all values are set properly'
            ]
            self.error_msg = ErrorMessageBox(_message)
            self.error_msg.show()
            return

        except RuntimeWarning:
            _message = [
                '\'N\' out of range!', 'Please increase N\nDefault: 12'
            ]
            self.error_msg = ErrorMessageBox(_message)
            self.error_msg.show()
            return

        if not _window_length % 2:
            _message = [
                'Error!',
                'Please ensure window_length is positive odd integer!'
            ]
            self.error_msg = ErrorMessageBox(_message)
            self.error_msg.show()
            return

        if _poly_order >= _window_length:
            _message = ['Error!', 'Please ensure poly_order < window_length!']
            self.error_msg = ErrorMessageBox(_message)
            self.error_msg.show()
            return

        # Set minimisation options dictionary
        _minimisation_options = {
            'disp': _disp,
            'maxiter': _maxiter,
            'ftol': _ftol
        }
        # Add additional optiosn for l_bfgs_b method
        if _op_method == 'L-BFGS-B':
            _minimisation_options['maxfun'] = _maxfun
            _minimisation_options['gtol'] = _gtol

        _global_minimisation = self.global_min_settings_gb.isChecked()
        _global_min_options = {
            'disp': _bh_disp,
            'niter': _bh_niter,
            'T': _bh_temp,
            'stepsize': _bh_step_size,
            'interval': _bh_interval
        }

        # Set preferences dictionary to return
        self._preferences = {
            'append_log_mode': _append_log_mode,
            'data_units': _data_units,
            'window_length': _window_length,
            'poly_order': _poly_order,
            'rescale_AL': _rescale_AL,
            'fft_N': _fft_N,
            'mod_func_mode': _mod_func_mode,
            'op_method': _op_method,
            'minimisation_options': _minimisation_options,
            'global_minimisation': _global_minimisation,
            'global_min_options': _global_min_options,
            'xray_weight_mode': _xray_weight_mode
        }

        # handle for ValueError if nothing entered
        self.done(1)

    def get_preferences(self):
        return self._preferences
Ejemplo n.º 42
0
class Window(QMainWindow):
    def __init__(self, parent):
        QMainWindow.__init__(self, None)
        self.parent = parent

        #Initialization of the plugin system
        init_plugin_system()

        #Got the enabled plugin
        self.settings = QSettings()
        self.enabled_plugins = []
        for plugin in find_plugins():
            if self.settings.contains(plugin.__name__):
                if self.settings.value(plugin.__name__) == '2':
                    print('Enable plugin ', plugin)
                    self.enabled_plugins.append(plugin())  #FIXME

        self.findAndReplace = FindAndReplaceDlg()
        self.setupFileMenu()
        self.setupHelpMenu()

        try:
            self.setAttribute(Qt.WA_Maemo5AutoOrientation, True)
            self.setAttribute(Qt.WA_Maemo5StackedWindow, True)

            #Speed Hack for Maemo Kinetic scrolling
            self.area = QScrollArea(self)
            try:
                scroller = self.area.property(
                    "kineticScroller")  #.toPyObject()
                scroller.setEnabled(True)
            except:
                scroller = None
            self.setupEditor(self.area)
            self.area.setWidget(self.editor)
            self.area.setWidgetResizable(True)
            self.setCentralWidget(self.area)

        except AttributeError as err:
            print('Not on maemo', err)
            #Resize window if not maemo
            self.resize(800, 600)
            self.setupEditor()
            self.setCentralWidget(self.editor)

    def fileSave(self):
        try:
            self.editor.save()
        except (IOError, OSError) as e:
            QMessageBox.warning(
                self, "KhtEditor -- Save Error",
                "Failed to save %s: %s" % (self.editor.filename, e))

    def saveAsFile(self):
        filename = QFileDialog.getSaveFileName(
            self, "KhtEditor -- Save File As", self.editor.filename,
            u'Python file(*.py);;' + u'Text file(*.txt);;' + u'C File(*.c);;' +
            u'C++ File(*.cpp)')
        if not (filename == ''):
            self.editor.filename = filename
            self.setWindowTitle(QFileInfo(filename).fileName())
            self.fileSave()
        return filename

    def openFile(self, path=''):
        filename = QFileDialog.getOpenFileName(self, "KhtEditor -- Open File",
                                               path)
        if not (filename == ''):
            self.loadFile(filename)
        return filename

    def loadFile(self, filename):
        self.editor.filename = filename
        try:
            self.editor.load()
            #             QTimer.singleShot(100, self.editor.load)
            self.setWindowTitle(QFileInfo(self.editor.filename).fileName())
#             QTimer.singleShot(100, self.loadHighlighter)
#            self.loadHighlighter(filename)

        except (IOError, OSError) as e:
            QMessageBox.warning(self, "KhtEditor -- Load Error",
                                "Failed to load %s: %s" % (filename, e))

    def setupEditor(self, scroller=None):
        self.editor = editor.KhtTextEdit(self)
        self.editor.scroller = scroller
        self.editor.show_progress.connect(self.show_progress)
        self.setupToolBar()
        self.editor.document().modificationChanged.connect(
            self.do_documentChanged)

    @pyqtSlot(bool)
    def show_progress(self, show):
        try:
            self.setAttribute(Qt.WA_Maemo5ShowProgressIndicator, show)
        except AttributeError:
            print('Not on maemo')

    def setupToolBar(self):
        self.toolbar = self.addToolBar('Toolbar')

        commentIcon = QIcon.fromTheme("general_tag")
        prefix = os.path.join(os.path.dirname(__file__), 'icons')
        indentIcon = QIcon(os.path.join(prefix, 'tb_indent.png'))

        unindentIcon = QIcon(os.path.join(prefix, 'tb_unindent.png'))
        saveIcon = QIcon.fromTheme("notes_save")
        fullscreenIcon = QIcon.fromTheme("general_fullsize")
        executeIcon = QIcon.fromTheme("general_forward")
        findIcon = QIcon.fromTheme("general_search")

        self.lineCount = QLabel('L.1 C.1')
        self.toolbar.addWidget(self.lineCount)
        self.editor.cursorPositionChanged.connect(self.lineCountUpdate)
        self.tb_comment = QAction(commentIcon, 'Comment', self)
        self.tb_comment.triggered.connect(self.editor.comment)
        self.toolbar.addAction(self.tb_comment)
        self.tb_indent = QAction(indentIcon, 'Indent', self)
        self.tb_indent.setShortcut('Ctrl+I')
        self.tb_indent.triggered.connect(self.editor.indent)
        self.toolbar.addAction(self.tb_indent)
        self.tb_unindent = QAction(unindentIcon, 'Unindent', self)
        self.tb_unindent.setShortcut('Ctrl+U')
        self.tb_unindent.triggered.connect(self.editor.unindent)
        self.toolbar.addAction(self.tb_unindent)
        self.tb_find = QAction(findIcon, 'Find', self)
        self.tb_find.setShortcut('Ctrl+F')
        self.tb_find.triggered.connect(self.do_find)
        self.toolbar.addAction(self.tb_find)
        self.tb_save = QAction(saveIcon, 'Save', self)
        self.tb_save.setShortcut('Ctrl+S')
        self.tb_save.triggered.connect(self.fileSave)
        self.toolbar.addAction(self.tb_save)
        self.tb_execute = QAction(executeIcon, 'Execute', self)
        self.tb_execute.setShortcut('Ctrl+E')
        self.tb_execute.triggered.connect(self.do_execute)
        self.toolbar.addAction(self.tb_execute)
        self.tb_fullscreen = QAction(fullscreenIcon, 'Fullscreen', self)
        self.tb_fullscreen.triggered.connect(self.do_fullscreen)
        self.toolbar.addAction(self.tb_fullscreen)

        #Actions not in toolbar
        self.tb_duplicate = QAction('Duplicate', self)
        self.tb_duplicate.setShortcut('Ctrl+D')
        self.tb_duplicate.triggered.connect(self.editor.duplicate)
        self.addAction(self.tb_duplicate)
        self.tb_findagain = QAction('Find Again', self)
        self.tb_findagain.setShortcut('Ctrl+G')
        self.tb_findagain.triggered.connect(self.findAndReplace.findClicked)
        self.addAction(self.tb_findagain)

        #Plugins menu
        self.tb_plugin_menu = QMenu(self)
        self.tb_plugin_button = QToolButton(self)
        self.tb_plugin_button.setText('Plugins')
        self.tb_plugin_button.setMenu(self.tb_plugin_menu)
        self.tb_plugin_button.setPopupMode(QToolButton.InstantPopup)
        self.tb_plugin_button.setCheckable(False)
        self.toolbar.addWidget(self.tb_plugin_button)

        #Hook for plugins to add buttons in combo box:
        for plugin in filter_plugins_by_capability('toolbarHook',
                                                   self.enabled_plugins):
            print('Found 1 Plugin for toolbarHook')
            plugin.do_toolbarHook(self.tb_plugin_menu)

    def setupFileMenu(self):
        fileMenu = QMenu(self.tr("&File"), self)
        self.menuBar().addMenu(fileMenu)

        fileMenu.addAction(self.tr("New..."), self.parent.newFile,
                           QKeySequence(self.tr("Ctrl+N", "New")))
        fileMenu.addAction(self.tr("Open..."), self.parent.openFile,
                           QKeySequence(self.tr("Ctrl+O", "Open")))
        fileMenu.addAction(self.tr("Save As"), self.saveAsFile,
                           QKeySequence(self.tr("Ctrl+Maj+S", "Save As")))

    def setupHelpMenu(self):
        helpMenu = QMenu(self.tr("&Help"), self)
        self.menuBar().addMenu(helpMenu)

        helpMenu.addAction(self.tr("&About"), self.do_about)

    @pyqtSlot()
    def do_about(self):
        self.parent.about(self)

    @pyqtSlot(six.integer_types[0])
    def do_gotoLine(self, line):
        print('goto line:' + str(line))
        self.editor.gotoLine(line)

    @pyqtSlot()
    def do_find(self):
        self.findAndReplace.find.connect(self.editor.find)
        self.findAndReplace.replace.connect(self.editor.replace)
        self.findAndReplace.replaceAll.connect(self.editor.replace_all)
        self.findAndReplace.show()

    @pyqtSlot()
    def do_execute(self):
        print("execute")
        #ask for save if unsaved
        self.fileSave()

        if self.editor.filename != None:
            try:
                fileHandle = open('/tmp/khteditor.tmp', 'wb')
                fileHandle.write('#!/bin/sh\n')
                fileHandle.write('cd ' + os.path.dirname(
                    unicode(self.editor.filename).encode('utf-8')) + ' \n')
                language = self.editor.detectLanguage(self.editor.filename)
                #Crappy way to handle that
                if language == 'python':
                    fileHandle.write(
                        "python \'" +
                        unicode(self.editor.filename).encode('utf-8') + "\'\n")
                elif language == 'qml':
                    fileHandle.write(
                        "qmlviewer \'" +
                        unicode(self.editor.filename).encode('utf-8') +
                        "\' -fullscreen\n")
                elif language in ('c', 'cpp'):
                    fileHandle.write("make %s\nchmod +x %s\n./%s" % (unicode(self.editor.filename).encode('utf-8'),\
                                                                     unicode(self.editor.filename).encode('utf-8'),\
                                                                     unicode(self.editor.filename).encode('utf-8')))
                elif language != None:
                    fileHandle.write(
                        language + " \'" +
                        unicode(self.editor.filename).encode('utf-8') +
                        "\' \n")
                else:
                    fileHandle.write(
                        "\'" + unicode(self.editor.filename).encode('utf-8') +
                        "\' \n")
                fileHandle.write('read -p "Press ENTER to continue ..." foo')
                fileHandle.write('\nexit')
                fileHandle.close()
            except (IOError, OSError) as e:
                QMessageBox.warning(
                    self, "KhtEditor -- Execute Error",
                    "Failed to write launch script %s: %s" %
                    (self.editor.filename, e))
            #commands.getoutput("chmod 777 /tmp/khteditor.tmp")
            check_call("chmod 777 /tmp/khteditor.tmp")
            Popen('/usr/bin/osso-xterm /tmp/khteditor.tmp',
                  shell=True,
                  stdout=None)

    @pyqtSlot()
    def lineCountUpdate(self):
        cursor = self.editor.textCursor()
        self.lineCount.setText(
            "L.%d C.%d" %
            (cursor.blockNumber() + 1, cursor.columnNumber() + 1))

    def closeEvent(self, event):
        self.editor.closeEvent(event)

    @pyqtSlot()
    def do_fullscreen(self):
        if self.isFullScreen():
            self.showMaximized()
        else:
            self.showFullScreen()

    @pyqtSlot(bool)
    def do_documentChanged(self, changed):
        if changed == True:
            self.setWindowTitle('*' +
                                QFileInfo(self.editor.filename).fileName())
        else:
            self.setWindowTitle(QFileInfo(self.editor.filename).fileName())
    def setup_ui(self):
        """Initialize widgets.
        """
        # ==== label =====
        self.lbl_vid = QLabel()
        #self.lbl_vid.setFixedSize(self.video_size)
        lbl_filename=QLabel("Filename:")

        # self.lbl_img_match=QLabel()
        # self.lbl_img_match.setPixmap(QPixmap(_dirIcon+"m1.jpg").scaled(100, 100, Qt.KeepAspectRatio, Qt.FastTransformation))
        # self.lbl_img_match.setFixedSize(QSize(100,100))

        self.lbl_img_pair=QLabel(" TEST")
        self.lbl_img_pair.setFixedSize(QSize(100,100))

        lbl_imgIn=QLabel("Img IN")
        lbl_imgIn.setFixedWidth(100)
        lbl_imgComp=QLabel("Img Comp")
        lbl_imgComp.setFixedWidth(100)
        lbl_checkin=QLabel("Checkin time")
        lbl_checkin.setFixedWidth(100)
        lbl_checkout=QLabel("Checkout time")
        lbl_checkout.setFixedWidth(100)

        self.lbl_imag_match_list=[]
        self.lbl_imag_pair_list=[]
        self.lbl_txt_checkIN=[]
        self.lbl_txt_checkOUT=[]

        ##### TEXTBOX ######
        self.tbox_filename=QLineEdit("")
        self.tbox_filename.setText(self._KnowfaceDIR)
        self.tbox_filename.setEnabled(False)

        ########## BUTTON ###################
        # self.btn_filename=QPushButton("...")
        # self.btn_filename.clicked.connect(self._browseFileLocation)
        # self.btn_filename.setFixedSize(QSize(monitorWidth*0.02,monitorHeight*0.02))

        self.btn_back=QPushButton("<< Back")

        self.btn_quit = QPushButton("Quit")
        self.btn_quit.clicked.connect(self._close)


####@@@@ Layout design @@@@####
        Htopleft=QHBoxLayout()
        Htopleft.addWidget(lbl_filename)
        Htopleft.addWidget(self.tbox_filename)
        # Htopleft.addWidget(self.btn_filename)

        VRight=QFormLayout()
        VRight.addRow(Htopleft)


        self.formLayout=QFormLayout()

        # ==== layout ====
        Vlayout_header=QHBoxLayout()
        Vlayout_header.addWidget(lbl_imgIn)
        Vlayout_header.addWidget(lbl_imgComp)
        Vlayout_header.addWidget(lbl_checkin)
        Vlayout_header.addWidget(lbl_checkout)

        self.formLayout.addRow(Vlayout_header)

        self.groupBox=QGroupBox(datetime.now().strftime("%d %b, %Y"))
        self.draw_match_pair_box()
        self.groupBox.setLayout(self.formLayout)

        scroll = QScrollArea()
        scroll.setWidget(self.groupBox)
        scroll.setWidgetResizable(True)
        scroll.setFixedHeight(self.video_size.height())
        scrollWidth=0
        if self.lbl_imag_match_list is not None and self.lbl_imag_pair_list is not None:
            scrollWidth=(self.lbl_imag_match_list[0].width() *4 *1.1)
        scroll.setFixedWidth(scrollWidth)

        VRight.addWidget(scroll)
        VRight.addWidget(self.btn_back)
        VRight.addWidget(self.btn_quit)

        self.main_layout = QHBoxLayout()
        self.main_layout.addWidget(self.lbl_vid)
        self.main_layout.addLayout(VRight)

        self.move(monitorWidth*0.15, monitorHeight*0.15)
        self.setLayout(self.main_layout)
Ejemplo n.º 44
0
class ResultHandler(QDialog):
    def __init__(self, parent=None):
        super(ResultHandler, self).__init__()
        self.setWindowTitle('Dash results')
        self.control_label = QLabel()
        self.rendered_label = QLabel()
        self.diff_label = QLabel()

        self.mask_label = QLabel()
        self.new_mask_label = QLabel()

        self.scrollArea = QScrollArea()
        self.widget = QWidget()

        self.test_name_label = QLabel()
        grid = QGridLayout()
        grid.addWidget(self.test_name_label, 0, 0)
        grid.addWidget(QLabel('Control'), 1, 0)
        grid.addWidget(QLabel('Rendered'), 1, 1)
        grid.addWidget(QLabel('Difference'), 1, 2)
        grid.addWidget(self.control_label, 2, 0)
        grid.addWidget(self.rendered_label, 2, 1)
        grid.addWidget(self.diff_label, 2, 2)
        grid.addWidget(QLabel('Current Mask'), 3, 0)
        grid.addWidget(QLabel('New Mask'), 3, 1)
        grid.addWidget(self.mask_label, 4, 0)
        grid.addWidget(self.new_mask_label, 4, 1)

        self.widget.setLayout(grid)
        self.scrollArea.setWidget(self.widget)
        v_layout = QVBoxLayout()
        v_layout.addWidget(self.scrollArea, 1)

        next_image_button = QPushButton()
        next_image_button.setText('Skip')
        next_image_button.pressed.connect(self.load_next)

        self.overload_spin = QDoubleSpinBox()
        self.overload_spin.setMinimum(1)
        self.overload_spin.setMaximum(255)
        self.overload_spin.setValue(1)
        self.overload_spin.valueChanged.connect(
            lambda: save_mask_button.setEnabled(False))

        preview_mask_button = QPushButton()
        preview_mask_button.setText('Preview New Mask')
        preview_mask_button.pressed.connect(self.preview_mask)
        preview_mask_button.pressed.connect(
            lambda: save_mask_button.setEnabled(True))

        save_mask_button = QPushButton()
        save_mask_button.setText('Save New Mask')
        save_mask_button.pressed.connect(self.save_mask)

        button_layout = QHBoxLayout()
        button_layout.addWidget(next_image_button)
        button_layout.addWidget(QLabel('Mask diff multiplier:'))
        button_layout.addWidget(self.overload_spin)
        button_layout.addWidget(preview_mask_button)
        button_layout.addWidget(save_mask_button)
        button_layout.addStretch()
        v_layout.addLayout(button_layout)
        self.setLayout(v_layout)

    def closeEvent(self, event):
        self.reject()

    def parse_url(self, url):
        print('Fetching dash results from: {}'.format(url))
        page = urllib.request.urlopen(url)
        soup = BeautifulSoup(page, "lxml")

        # build up list of rendered images
        measurement_img = [
            img for img in soup.find_all('img')
            if img.get('alt') and img.get('alt').startswith('Rendered Image')
        ]

        images = {}
        for img in measurement_img:
            m = re.search('Rendered Image (.*?)(\s|$)', img.get('alt'))
            test_name = m.group(1)
            rendered_image = img.get('src')
            images[test_name] = '{}/{}'.format(dash_url, rendered_image)

        if images:
            print('found images:\n{}'.format(images))
        else:
            print('no images found\n')
        self.images = images
        self.load_next()

    def load_next(self):
        if not self.images:
            # all done
            self.accept()
            exit(0)

        test_name, rendered_image = self.images.popitem()
        self.test_name_label.setText(test_name)
        control_image = self.get_control_image_path(test_name)
        if not control_image:
            self.load_next()
            return

        self.mask_image_path = control_image[:-4] + '_mask.png'
        self.load_images(control_image, rendered_image, self.mask_image_path)

    def load_images(self, control_image_path, rendered_image_path,
                    mask_image_path):
        self.control_image = imageFromPath(control_image_path)
        if not self.control_image:
            error('Could not read control image {}'.format(control_image_path))

        self.rendered_image = imageFromPath(rendered_image_path)
        if not self.rendered_image:
            error(
                'Could not read rendered image {}'.format(rendered_image_path))
        if not self.rendered_image.width() == self.control_image.width(
        ) or not self.rendered_image.height() == self.control_image.height():
            print(
                'Size mismatch - control image is {}x{}, rendered image is {}x{}'
                .format(self.control_image.width(),
                        self.control_image.height(),
                        self.rendered_image.width(),
                        self.rendered_image.height()))

        max_width = min(self.rendered_image.width(),
                        self.control_image.width())
        max_height = min(self.rendered_image.height(),
                         self.control_image.height())

        # read current mask, if it exist
        self.mask_image = imageFromPath(mask_image_path)
        if self.mask_image.isNull():
            print('Mask image does not exist, creating {}'.format(
                mask_image_path))
            self.mask_image = QImage(self.control_image.width(),
                                     self.control_image.height(),
                                     QImage.Format_ARGB32)
            self.mask_image.fill(QColor(0, 0, 0))

        self.diff_image = self.create_diff_image(self.control_image,
                                                 self.rendered_image,
                                                 self.mask_image)
        if not self.diff_image:
            self.load_next()
            return

        self.control_label.setPixmap(QPixmap.fromImage(self.control_image))
        self.rendered_label.setPixmap(QPixmap.fromImage(self.rendered_image))
        self.mask_label.setPixmap(QPixmap.fromImage(self.mask_image))
        self.diff_label.setPixmap(QPixmap.fromImage(self.diff_image))
        self.preview_mask()

    def preview_mask(self):
        self.new_mask_image = self.create_mask(self.control_image,
                                               self.rendered_image,
                                               self.mask_image,
                                               self.overload_spin.value())
        self.new_mask_label.setPixmap(QPixmap.fromImage(self.new_mask_image))

    def save_mask(self):
        self.new_mask_image.save(self.mask_image_path, "png")
        self.load_next()

    def create_mask(self,
                    control_image,
                    rendered_image,
                    mask_image,
                    overload=1):
        max_width = min(rendered_image.width(), control_image.width())
        max_height = min(rendered_image.height(), control_image.height())

        new_mask_image = QImage(control_image.width(), control_image.height(),
                                QImage.Format_ARGB32)
        new_mask_image.fill(QColor(0, 0, 0))

        # loop through pixels in rendered image and compare
        mismatch_count = 0
        linebytes = max_width * 4
        for y in range(max_height):
            control_scanline = control_image.constScanLine(y).asstring(
                linebytes)
            rendered_scanline = rendered_image.constScanLine(y).asstring(
                linebytes)
            mask_scanline = mask_image.scanLine(y).asstring(linebytes)

            for x in range(max_width):
                currentTolerance = qRed(
                    struct.unpack('I', mask_scanline[x * 4:x * 4 + 4])[0])

                if currentTolerance == 255:
                    # ignore pixel
                    new_mask_image.setPixel(
                        x, y,
                        qRgb(currentTolerance, currentTolerance,
                             currentTolerance))
                    continue

                expected_rgb = struct.unpack(
                    'I', control_scanline[x * 4:x * 4 + 4])[0]
                rendered_rgb = struct.unpack(
                    'I', rendered_scanline[x * 4:x * 4 + 4])[0]
                difference = min(
                    255,
                    colorDiff(expected_rgb, rendered_rgb) * overload)

                if difference > currentTolerance:
                    # update mask image
                    new_mask_image.setPixel(
                        x, y, qRgb(difference, difference, difference))
                    mismatch_count += 1
                else:
                    new_mask_image.setPixel(
                        x, y,
                        qRgb(currentTolerance, currentTolerance,
                             currentTolerance))
        return new_mask_image

    def get_control_image_path(self, test_name):
        if os.path.isfile(test_name):
            return path

        # else try and find matching test image
        script_folder = os.path.dirname(os.path.realpath(sys.argv[0]))
        control_images_folder = os.path.join(
            script_folder, '../tests/testdata/control_images')

        matching_control_images = [
            x[0] for x in os.walk(control_images_folder) if test_name in x[0]
        ]
        if len(matching_control_images) > 1:
            QMessageBox.warning(
                self, 'Result',
                'Found multiple matching control images for {}'.format(
                    test_name))
            return None
        elif len(matching_control_images) == 0:
            QMessageBox.warning(
                self, 'Result',
                'No matching control images found for {}'.format(test_name))
            return None

        found_control_image_path = matching_control_images[0]

        # check for a single matching expected image
        images = glob.glob(os.path.join(found_control_image_path, '*.png'))
        filtered_images = [i for i in images if not i[-9:] == '_mask.png']
        if len(filtered_images) > 1:
            error('Found multiple matching control images for {}'.format(
                test_name))
        elif len(filtered_images) == 0:
            error('No matching control images found for {}'.format(test_name))

        found_image = filtered_images[0]
        print('Found matching control image: {}'.format(found_image))
        return found_image

    def create_diff_image(self, control_image, rendered_image, mask_image):
        # loop through pixels in rendered image and compare
        mismatch_count = 0
        max_width = min(rendered_image.width(), control_image.width())
        max_height = min(rendered_image.height(), control_image.height())
        linebytes = max_width * 4

        diff_image = QImage(control_image.width(), control_image.height(),
                            QImage.Format_ARGB32)
        diff_image.fill(QColor(152, 219, 249))

        for y in range(max_height):
            control_scanline = control_image.constScanLine(y).asstring(
                linebytes)
            rendered_scanline = rendered_image.constScanLine(y).asstring(
                linebytes)
            mask_scanline = mask_image.scanLine(y).asstring(linebytes)

            for x in range(max_width):
                currentTolerance = qRed(
                    struct.unpack('I', mask_scanline[x * 4:x * 4 + 4])[0])

                if currentTolerance == 255:
                    # ignore pixel
                    continue

                expected_rgb = struct.unpack(
                    'I', control_scanline[x * 4:x * 4 + 4])[0]
                rendered_rgb = struct.unpack(
                    'I', rendered_scanline[x * 4:x * 4 + 4])[0]
                difference = colorDiff(expected_rgb, rendered_rgb)

                if difference > currentTolerance:
                    # update mask image
                    diff_image.setPixel(x, y, qRgb(255, 0, 0))
                    mismatch_count += 1

        if mismatch_count:
            return diff_image
        else:
            print('No mismatches')
            return None
Ejemplo n.º 45
0
    def get_scroller(self):
        scroller_area = QScrollArea(self)
        scroller_area.setVisible(True)
        scroller_area.setWidgetResizable(True)
        try:
            with open('scroller.css', 'r') as css:
                scroller_area.setStyleSheet(css.read())
        except OSError:
            pass

        scroller_content = QWidget()
        scroller_layout = QVBoxLayout()
        scroller_layout.setSpacing(0)
        scroller_layout.setStretch(0, 1)
        self.load_cbz(scroller_layout, self.filepath)

        scroller_layout.addWidget(self.get_footer())
        scroller_layout.setContentsMargins(0, 0, 0, 0)
        scroller_content.setLayout(scroller_layout)
        scroller_area.setWidget(scroller_content)
        scroller_area.setWidgetResizable(True)
        scroller_area.verticalScrollBar().setSingleStep(30)
        self.scroller = scroller_area
        return scroller_area
Ejemplo n.º 46
0
    def initUI(self):
        self.setGeometry(200, 150, 500, 500)
        self.setWindowTitle('Заказ в Ресторане')

        self.IsMenuLoaded = False

        self.DescriptionLabel = QPlainTextEdit(
            '   Программа оформления заказов в ресторане\n\n\n      Проект для Яндекс.Лицея по теме PyQt5\n\n\n                         Холяна Тимофея'
        )
        self.DescriptionLabel.setReadOnly(True)

        self.Help1 = QLabel('Укажите путь до базы данных')

        self.PathToDB = QLineEdit()

        self.OpenDBFile = QPushButton('...')
        self.OpenDBFile.clicked.connect(self.on_select_file)

        self.StartBtn = QPushButton('Старт')
        self.StartBtn.clicked.connect(self.on_start)

        self.OpenFileLayout = QHBoxLayout()
        self.OpenFileLayout.addWidget(self.PathToDB)
        self.OpenFileLayout.addWidget(self.OpenDBFile)

        self.FirstScreen = QVBoxLayout()
        self.FirstScreen.addWidget(self.DescriptionLabel,
                                   alignment=Qt.AlignCenter)
        self.FirstScreen.addWidget(self.Help1, alignment=Qt.AlignCenter)
        self.FirstScreen.addLayout(self.OpenFileLayout)
        self.FirstScreen.addWidget(self.StartBtn, alignment=Qt.AlignCenter)
        self.FirstScreen.addStretch(1)  # Стартовый экран

        self.DateTime = QLineEdit()
        self.DateTime.setReadOnly(True)  # Показываем время

        self.ordernum = QLineEdit()
        self.ordernum.setReadOnly(True)  # Номер заказа

        self.Header1 = QHBoxLayout()
        self.Header1.addWidget(self.DateTime,
                               alignment=Qt.AlignLeft | Qt.AlignTop)
        self.Header1.addWidget(
            self.ordernum, alignment=Qt.AlignRight
            | Qt.AlignTop)  # Эти два виджета центтрируем по верхним углам

        self.SaveOrderBtn = QPushButton('Оформить заказ')
        self.SaveOrderBtn.clicked.connect(self.get_receipt)

        self.StatsBtn = QPushButton('Отчёт')
        self.StatsBtn.clicked.connect(self.get_stats)

        self.MenuLayout = QGridLayout()  # будем распологать элементы сеткой

        self.MenuForm = QWidget()
        self.MenuForm.setLayout(self.MenuLayout)

        self.Menu1 = QScrollArea()
        self.Menu1.setWidget(self.MenuForm)
        self.Menu1.setWidgetResizable(True)  # Добавим возможность перемотки

        self.Footer1 = QHBoxLayout()
        self.Footer1.addWidget(self.SaveOrderBtn,
                               alignment=Qt.AlignCenter | Qt.AlignBottom)
        self.Footer1.addWidget(self.StatsBtn,
                               alignment=Qt.AlignCenter | Qt.AlignBottom)

        self.Help2 = QLabel('Сумма заказа: ')

        self.TotalMoney = QLineEdit()
        self.TotalMoney.setReadOnly(True)
        self.TotalMoney.setFixedWidth(200)

        self.Footer2 = QHBoxLayout()
        self.Footer2.addWidget(self.Help2,
                               alignment=Qt.AlignLeft | Qt.AlignCenter)
        self.Footer2.addWidget(self.TotalMoney,
                               alignment=Qt.AlignLeft | Qt.AlignBottom)
        self.Footer2.addStretch(1)

        self.MainScreen = QVBoxLayout()
        self.MainScreen.addLayout(self.Header1)
        self.MainScreen.addWidget(self.Menu1, stretch=1)
        self.MainScreen.addLayout(self.Footer2)
        self.MainScreen.addLayout(
            self.Footer1)  # Добавляем на основной экран нужные виджеты

        self.Notification = QLabel('Заказ прошёл успешно')

        self.Receipt = QPlainTextEdit()
        self.Receipt.setReadOnly(True)

        self.Back1 = QPushButton('Назад')
        self.Back1.clicked.connect(self.start_main)

        self.OrderScreen = QVBoxLayout()
        self.OrderScreen.addWidget(self.Notification,
                                   alignment=Qt.AlignCenter | Qt.AlignTop)
        self.OrderScreen.addWidget(self.Receipt, stretch=1)
        self.OrderScreen.addWidget(self.Back1,
                                   alignment=Qt.AlignCenter
                                   | Qt.AlignBottom)  # Создали экран с чеком

        self.Stats = QPlainTextEdit()
        self.Stats.setReadOnly(True)

        self.Back2 = QPushButton('Назад')
        self.Back2.clicked.connect(self.back_to_main)

        self.StatsScreen = QVBoxLayout()
        self.StatsScreen.addWidget(self.Stats, stretch=1)
        self.StatsScreen.addWidget(
            self.Back2, alignment=Qt.AlignCenter
            | Qt.AlignBottom)  # Создали экран со статистикой

        self.StLayout = QStackedLayout(
        )  # Виджет для отображения нескольких экранов в одном окне

        self.Frame1 = QFrame(self)
        self.Frame1.setLayout(self.FirstScreen)  # Собственно первый экран

        self.StLayout.addWidget(self.Frame1)

        self.setLayout(self.StLayout)
Ejemplo n.º 47
0
	def initUI(self):
		self.setWindowTitle(self.title)
		self.setGeometry(self.left, self.top, self.width, self.height)

		self.createTable()
		self.crearLista()
		self.crearListaDeRegistros()

		self.pila = []
		self.base = []
		vbox = QBoxLayout(3)

		for x in range(11):
			self.base.append(QLabel())
			label = self.base[x]
			label.setText("xxxxxxxxxx")
			vbox.addWidget(label)
		self.base[10].setText("")
		for x in range(256):
			self.pila.append(QLabel())
			label = self.pila[x]
			vbox.addWidget(label)
		fondoPILA = self.pila[0]
		fondoPILA.setText("FONDO")

		button = QPushButton('Trazo', self)
		button.pressed.connect(self.desensambladoTrazo)

		self.button2 = QPushButton('Paso a Paso', self)
		self.button2.pressed.connect(self.ponerPasoAPaso)

		container = QWidget()
		self.ly = QBoxLayout(0)
		self.ly.addWidget(button)
		self.ly.addWidget(self.button2)
		container.setLayout(self.ly)

		win = QWidget()
		area = QScrollArea()

		win.setLayout(vbox)
		area.setWidget(win)
		area.verticalScrollBar().setValue(area.verticalScrollBar().maximum())
		area.setStyleSheet("background-color: #90caf9")
		self.GRIDPRINCIPAL = QGridLayout()
		GRID2 = QGridLayout()
		contenedor = QWidget()

		codigo = QWidget()
		contcodigo = QBoxLayout(2)
		codigo.setStyleSheet("background-color: #f48fb1")

		desFont = QFont("Times", 14, QFont.Bold)
		self.mostrarDesensamble = []

		for x in range(9):
			self.mostrarDesensamble.append(QLabel())
			self.mostrarDesensamble[x].setFont(desFont)
			contcodigo.addWidget(self.mostrarDesensamble[x])
			self.mostrarDesensamble[x].setStyleSheet("color: #000;")

		self.mostrarDesensamble[0].setText('Código Desensamblado')
		self.mostrarDesensamble[1].setText('PC		Código		Instrucción')
		self.mostrarDesensamble[8].setStyleSheet("QLabel { color: white; background-color: black; border-radius: 23px}")

		codigo.setLayout(contcodigo)
		self.mostrarDesensamble[0].setAlignment(Qt.AlignCenter)

		#boton ir a
		containerGoTO = QWidget()
		self.goTo = QLineEdit(self)
		self.goTo.setInputMask(">HHHH")
		self.goTo.setText("0000")
		addressLabel = QLabel()
		addressLabel.setText("Ir a")
		addressLabel1 = QLabel()
		addressLabel1.setText("dirección")
		addressLabel2 = QLabel()
		addressLabel2.setText("de memoria: ")
		self.box1 = QBoxLayout(2)
		self.box1.addWidget(addressLabel)
		self.box1.addWidget(addressLabel1)
		self.box1.addWidget(addressLabel2)
		self.box1.addWidget(self.goTo)
		containerGoTO.setLayout(self.box1)

		containerCleanMemory = QWidget()
		#boton desde
		self.clean1 = QLineEdit(self)
		self.clean1.setInputMask(">HHHH")
		self.clean1.setText("0000")
		cleanTextFrom = QLabel()
		cleanTextFrom.setText("Limpiar desde")
		#boton hasta
		self.clean2 = QLineEdit(self)
		self.clean2.setInputMask(">HHHH")
		self.clean2.setText("0000")
		cleanTextTo = QLabel()
		cleanTextTo.setText("hasta")
		#boton limpiar
		self.box2 = QBoxLayout(0)
		self.box2.addWidget(cleanTextFrom)
		self.box2.addWidget(self.clean1)
		self.box2.addWidget(cleanTextTo)
		self.box2.addWidget(self.clean2)
		containerCleanMemory.setLayout(self.box2)

		#buttons to clean
		containerCleanMemory1 = QWidget()
		self.cleanButton = QPushButton("Limpiar", self)
		self.cleanAll = QPushButton("Limpiar toda la memoria", self)
		self.box3 = QBoxLayout(0)
		self.box3.addWidget(self.cleanButton)
		self.box3.addWidget(self.cleanAll)
		containerCleanMemory1.setLayout(self.box3)

		self.dSpinBoxF = QDoubleSpinBox()
		self.dSpinBoxF.setMinimum(2.5)
		self.dSpinBoxF.setMaximum(9000)
		self.dSpinBoxF.setValue(3.58)
		self.dSpinBoxF.setSingleStep(0.01)

		containerEjec = QWidget()
		timeFrecWid = QWidget()
		allTime = QWidget()

		self.timeTitle = QLabel()
		self.timeSub = QLabel()
		self.instCiclos = QLabel()
		self.instTime = QLabel()
		self.totalTime = QLabel()
		self.labelZ = QLabel()
		self.labelY = QLabel()

		self.labelZ.setFixedSize(45, 48)
		self.labelY.setFixedSize(55, 48)
		self.totalTime.setFixedSize(110, 48)
		self.instTime.setFixedSize(110, 48)
		self.instCiclos.setFixedSize(30, 30)

		self.timeTitle.setText("Tiempo de Ejecución")
		self.timeSub.setText("     Frecuencia              CiclosT    Instrucción   	    Total")
		self.instCiclos.setText("    ")
		self.instTime.setText("       ")
		self.totalTime.setText("       ")
		self.labelZ.setText("[MHz]")
		self.labelY.setText("[MicroS]")

		frecTime = QHBoxLayout()
		uneTime = QVBoxLayout()
		layTime = QVBoxLayout()

		self.timeTitle.setAlignment(Qt.AlignCenter)
		self.instTime.setAlignment(Qt.AlignCenter)
		self.totalTime.setAlignment(Qt.AlignCenter)
		self.labelZ.setAlignment(Qt.AlignCenter)
		self.labelY.setAlignment(Qt.AlignCenter)
		self.instCiclos.setAlignment(Qt.AlignCenter)

		frecTime.addWidget(self.dSpinBoxF)
		frecTime.addWidget(self.labelZ)
		frecTime.addWidget(self.instCiclos)
		frecTime.addWidget(self.instTime)
		frecTime.addWidget(self.totalTime)
		frecTime.addWidget(self.labelY)
		timeFrecWid.setLayout(frecTime)
		uneTime.addWidget(self.timeTitle)
		uneTime.addWidget(self.timeSub)
		uneTime.addWidget(timeFrecWid)
		allTime.setLayout(uneTime)

		layTime.addWidget(containerCleanMemory1)
		layTime.addWidget(allTime)
		containerEjec.setLayout(layTime)

		self.containerAdress = QWidget()
		self.textbox = QLineEdit(self)
		self.textbox.setInputMask(">HHHH")
		self.textbox.setText("0000")
		addressLabel = QLabel()
		addressLabel.setText("Dir. Ejecución")
		self.box1 = QBoxLayout(2)
		self.box1.addWidget(addressLabel)
		self.box1.addWidget(self.textbox)
		self.containerAdress.setLayout(self.box1)
		self.textbox.textEdited.connect(self.asignarPC)

		memLbl = QLabel()
		memLbl.setText('Memoria')
		memLbl.setAlignment(Qt.AlignCenter)
		pilaLbl = QLabel()
		pilaLbl.setText('Stack')
		pilaLbl.setAlignment(Qt.AlignCenter)
		memLbl.setStyleSheet("font-size: 12px;font-weight: bold")
		pilaLbl.setStyleSheet("font-size: 12px;font-weight: bold")

		GRID2.addWidget(self.win2, 0, 0)
		GRID2.addWidget(self.win3, 1, 0)
		GRID2.addWidget(self.win4, 2, 0)
		contenedor.setLayout(GRID2)
		self.GRIDPRINCIPAL.setColumnStretch(0, 5)
		self.GRIDPRINCIPAL.setColumnStretch(1, 1)
		self.GRIDPRINCIPAL.setColumnStretch(2, 4)
		self.GRIDPRINCIPAL.addWidget(memLbl, 0, 0)
		self.GRIDPRINCIPAL.addWidget(pilaLbl, 0, 1)
		self.GRIDPRINCIPAL.addWidget(self.tableWidget, 1, 0)
		self.GRIDPRINCIPAL.addWidget(area, 1, 1)
		self.GRIDPRINCIPAL.addWidget(codigo, 1, 2)
		self.GRIDPRINCIPAL.addWidget(container, 2, 0)  # Botones paso a paso y trazo
		self.GRIDPRINCIPAL.addWidget(self.containerAdress, 2, 1)  # Dir Ejecucion
		self.GRIDPRINCIPAL.addWidget(containerCleanMemory, 2, 2)  # From TO
		self.GRIDPRINCIPAL.addWidget(contenedor, 3, 0)  # Registros
		self.GRIDPRINCIPAL.addWidget(containerGoTO, 3, 1)  # IR a DIR
		self.GRIDPRINCIPAL.addWidget(containerEjec, 3, 2)

		self.goTo.textEdited.connect(self.goToPosition)
		self.goTo.editingFinished.connect(self.goToPosition)
		self.cleanButton.pressed.connect(self.LimpiarMemoria)
		self.cleanAll.pressed.connect(self.LimpiarMemoriaCompleta)
		self.dSpinBoxF.valueChanged.connect(self.changeFrec)
		self.setLayout(self.GRIDPRINCIPAL)

		#Estilos
		containerGoTO.setStyleSheet("background-color: #90caf9;color: #000;border: none; border-radius: 23px;font-size: 13px;font-weight: bold")
		self.goTo.setStyleSheet("background-color: #8bc34a;padding:10px 0;border-radius: 15px;margin: 5px")
		self.tableWidget.setStyleSheet("background-color: #f48fb1;color: #000; sans-serif;font-size: 13px;font-weight: bold;gridline-color: #fff;selection-background-color:  #c2185b;border: none")
		contenedor.setStyleSheet("background-color: #90caf9;font-size: 13px;font-weight: bold;border-radius: 23px")
		button.setStyleSheet("background-color: #8bc34a;border: none; border-radius: 23px;font-size:15px;font-weight: bold;padding:15px")
		self.button2.setStyleSheet("background-color: #8bc34a;border: none; border-radius: 23px;font-size:15px;font-weight: bold;padding:15px")

		self.clean1.setStyleSheet("background-color: #8bc34a;border: none; border-radius: 23px;font-size: 12px;font-weight: bold;padding:15px")
		self.clean2.setStyleSheet("background-color: #8bc34a;border: none; border-radius: 23px;font-size: 12px;font-weight: bold;padding:15px")
		cleanTextFrom.setStyleSheet("font-size: 12px;font-weight: bold")
		cleanTextTo.setStyleSheet("font-size: 12px;font-weight: bold")
		containerCleanMemory.setStyleSheet("background-color: #90caf9;padding: 15px; border-radius: 23px")
		self.cleanButton.setStyleSheet("background-color: #8bc34a;border: none; border-radius: 18px;font-size: 12px;font-weight: bold;padding:15px")
		self.cleanAll.setStyleSheet("background-color: #8bc34a;border: none; border-radius: 18px;font-size: 12px;font-weight: bold;padding:15px")
		self.containerAdress.setStyleSheet("background-color: #90caf9;color: #000;border: none; border-radius: 23px;font-size: 13px;font-weight: bold")
		self.textbox.setStyleSheet("background-color: #8bc34a;padding:10px 0;border-radius: 15px;margin: 5px")
		self.dSpinBoxF.setStyleSheet("background-color: #8bc34a;border: none; border-radius: 18px;font-size: 12px;font-weight: bold;padding:15px")

		containerEjec.setStyleSheet("background-color: #90caf9;color: #000;border: none; border-radius: 23px;font-size: 13px;font-weight: bold")
		self.labelY.setStyleSheet("background-color: #f48fb1;font-size: 12px;font-weight: bold")
		self.labelZ.setStyleSheet("background-color: #8bc34a;font-size: 12px;font-weight: bold")
		self.instTime.setStyleSheet("background-color: #f48fb1;border: none; border-radius: 23px;font-size:15px;font-weight: bold;padding:15px")
		self.totalTime.setStyleSheet("background-color: #f48fb1;border: none; border-radius: 23px;font-size:15px;font-weight: bold;padding:15px")
Ejemplo n.º 48
0
    def add_options_panel(self):
        # Prepare the sliders
        options_layout = QVBoxLayout()

        options_layout.addStretch()  # Centralize the sliders
        sliders_layout = QVBoxLayout()
        max_label_width = -1
        for i in range(self.model.nbDof()):
            slider_layout = QHBoxLayout()
            sliders_layout.addLayout(slider_layout)

            # Add a name
            name_label = QLabel()
            name = f"{self.model.nameDof()[i]}"
            name_label.setText(name)
            name_label.setPalette(self.palette_active)
            label_width = name_label.fontMetrics().boundingRect(name_label.text()).width()
            if label_width > max_label_width:
                max_label_width = label_width
            slider_layout.addWidget(name_label)

            # Add the slider
            slider = QSlider(Qt.Horizontal)
            slider.setMinimum(-np.pi*self.double_factor)
            slider.setMaximum(np.pi*self.double_factor)
            slider.setPageStep(self.double_factor)
            slider.setValue(0)
            slider.valueChanged.connect(self.__move_avatar_from_sliders)
            slider.sliderReleased.connect(partial(self.__update_muscle_analyses_graphs, False, False, False, False))
            slider_layout.addWidget(slider)

            # Add the value
            value_label = QLabel()
            value_label.setText(f"{0:.2f}")
            value_label.setPalette(self.palette_active)
            slider_layout.addWidget(value_label)

            # Add to the main sliders
            self.sliders.append((name_label, slider, value_label))
        # Adjust the size of the names
        for name_label, _, _ in self.sliders:
            name_label.setFixedWidth(max_label_width + 1)

        # Put the sliders in a scrollable area
        sliders_widget = QWidget()
        sliders_widget.setLayout(sliders_layout)
        sliders_scroll = QScrollArea()
        sliders_scroll.setFrameShape(0)
        sliders_scroll.setWidgetResizable(True)
        sliders_scroll.setWidget(sliders_widget)
        options_layout.addWidget(sliders_scroll)

        # Add reset button
        button_layout = QHBoxLayout()
        options_layout.addLayout(button_layout)
        reset_push_button = QPushButton("Reset")
        reset_push_button.setPalette(self.palette_active)
        reset_push_button.released.connect(self.reset_q)
        button_layout.addWidget(reset_push_button)

        # Add the radio button for analyses
        option_analyses_group = QGroupBox()
        option_analyses_layout = QVBoxLayout()
        # Add text
        analyse_text = QLabel()
        analyse_text.setPalette(self.palette_active)
        analyse_text.setText("Analyses")
        option_analyses_layout.addWidget(analyse_text)
        # Add the no analyses
        radio_none = QRadioButton()
        radio_none.setPalette(self.palette_active)
        radio_none.setChecked(True)
        radio_none.toggled.connect(lambda: self.__select_analyses_panel(radio_none, 0))
        radio_none.setText("None")
        option_analyses_layout.addWidget(radio_none)
        # Add the muscles analyses
        radio_muscle = QRadioButton()
        radio_muscle.setPalette(self.palette_active)
        radio_muscle.toggled.connect(lambda: self.__select_analyses_panel(radio_muscle, 1))
        radio_muscle.setText("Muscles")
        option_analyses_layout.addWidget(radio_muscle)
        # Add the layout to the interface
        option_analyses_group.setLayout(option_analyses_layout)
        options_layout.addWidget(option_analyses_group)

        # Finalize the options panel
        options_layout.addStretch()  # Centralize the sliders

        # Animation panel
        animation_layout = QVBoxLayout()
        animation_layout.addWidget(self.vtk_window.avatar_widget)

        # Add the animation slider
        animation_slider_layout = QHBoxLayout()
        animation_layout.addLayout(animation_slider_layout)
        load_push_button = QPushButton("Load movement")
        load_push_button.setPalette(self.palette_active)
        load_push_button.released.connect(self.__load_movement_from_button)
        animation_slider_layout.addWidget(load_push_button)

        # Controllers
        self.play_stop_push_button = QPushButton()
        self.play_stop_push_button.setIcon(self.start_icon)
        self.play_stop_push_button.setPalette(self.palette_active)
        self.play_stop_push_button.setEnabled(False)
        self.play_stop_push_button.released.connect(self.__start_stop_animation)
        animation_slider_layout.addWidget(self.play_stop_push_button)

        slider = QSlider(Qt.Horizontal)
        slider.setMinimum(0)
        slider.setMaximum(100)
        slider.setValue(0)
        slider.setEnabled(False)
        slider.valueChanged.connect(self.__animate_from_slider)
        animation_slider_layout.addWidget(slider)

        # Add the frame count
        frame_label = QLabel()
        frame_label.setText(f"{0}")
        frame_label.setPalette(self.palette_inactive)
        animation_slider_layout.addWidget(frame_label)

        self.movement_slider = (slider, frame_label)

        # Global placement of the window
        self.vtk_window.main_layout.addLayout(options_layout, 0, 0)
        self.vtk_window.main_layout.addLayout(animation_layout, 0, 1)
        self.vtk_window.main_layout.setColumnStretch(0, 1)
        self.vtk_window.main_layout.setColumnStretch(1, 2)

        # Change the size of the window to account for the new sliders
        self.vtk_window.resize(self.vtk_window.size().width() * 2, self.vtk_window.size().height())

        # Prepare all the analyses panel
        self.muscle_analyses = MuscleAnalyses(self.analyses_muscle_widget, self)
        if self.model.nbMuscleTotal() == 0:
            radio_muscle.setEnabled(False)
        self.__select_analyses_panel(radio_muscle, 1)
Ejemplo n.º 49
0
class UITenScripts(object):
    def __init__(self):
        self.kritaInstance = krita.Krita.instance()
        self.mainDialog = tenscriptsdialog.TenScriptsDialog(
            self,
            self.kritaInstance.activeWindow().qwindow())

        self.buttonBox = QDialogButtonBox(self.mainDialog)
        self.layout = QVBoxLayout(self.mainDialog)
        self.baseWidget = QWidget()
        self.baseArea = QWidget()
        self.scrollArea = QScrollArea()
        self.scriptsLayout = QGridLayout()

        self.buttonBox.accepted.connect(self.mainDialog.accept)
        self.buttonBox.rejected.connect(self.mainDialog.reject)

        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Ok
                                          | QDialogButtonBox.Cancel)
        self.scrollArea.setWidgetResizable(True)

    def initialize(self, tenscripts):
        self.tenscripts = tenscripts

        self._loadGridLayout()
        self._fillScripts()

        self.baseArea.setLayout(self.scriptsLayout)
        self.scrollArea.setWidget(self.baseArea)

        self.layout.addWidget(self.scrollArea)
        self.layout.addWidget(self.buttonBox)

        self.mainDialog.show()
        self.mainDialog.activateWindow()
        self.mainDialog.exec_()

    def addNewRow(self, key):
        rowPosition = self.scriptsLayout.rowCount()
        rowLayout = QHBoxLayout()
        label = QLabel()
        directoryTextField = QLineEdit()
        directoryDialogButton = QPushButton("...")

        directoryTextField.setReadOnly(True)
        label.setText("Ctrl+Shift+{0}".format(key))
        directoryTextField.setToolTip("Selected Path")
        directoryDialogButton.setToolTip("Select the script")
        directoryDialogButton.clicked.connect(self._selectScript)

        self.scriptsLayout.addWidget(label, rowPosition, 0,
                                     Qt.AlignLeft | Qt.AlignTop)
        self.scriptsLayout.addWidget(directoryTextField, rowPosition, 1,
                                     Qt.AlignLeft | Qt.AlignTop)
        self.scriptsLayout.addWidget(directoryDialogButton, rowPosition, 2,
                                     Qt.AlignLeft | Qt.AlignTop)

    def saved_scripts(self):
        _saved_scripts = []
        index = 0

        for row in range(self.scriptsLayout.rowCount() - 1):
            textField = self.scriptsLayout.itemAt(index + 1).widget()
            if textField.text():
                _saved_scripts.append(textField.text())
            index += 3

        return _saved_scripts

    def _selectScript(self):
        dialog = QFileDialog(self.mainDialog)
        dialog.setNameFilter('Python files (*.py)')

        if dialog.exec():
            selectedFile = dialog.selectedFiles()[0]
            obj = self.mainDialog.sender()
            textField = self.scriptsLayout.itemAt(
                self.scriptsLayout.indexOf(obj) - 1).widget()
            textField.setText(selectedFile)

    def _loadGridLayout(self):
        for item in ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']:
            self.addNewRow(item)

    def _fillScripts(self):
        scripts = self.tenscripts.scripts
        index = 0

        for row in range(self.scriptsLayout.rowCount() - 1):
            if row >= len(scripts):
                return

            textField = self.scriptsLayout.itemAt(index + 1).widget()
            textField.setText(scripts[row])
            index += 3
Ejemplo n.º 50
0
class SoloProWidget(QWidget):
    """Widget for the Solo Pro"""
    def __init__(self, textchanged):
        super(SoloProWidget, self).__init__()
        self.vbox_window = QVBoxLayout()
        self.setLayout(self.vbox_window)

        self.require = InputLabel("Required number of secrets : ", "2")
        self.require.textChanged.connect(self.on_required_change)
        self.vbox_window.addWidget(self.require)

        self.box_recover = QGroupBox()
        self.box_recover.setTitle('SOLO PRO')
        self.vbox_window.addWidget(self.box_recover)

        self.secrets_recover = None

        self.vbox_recover = QVBoxLayout()

        self.box_recover.setLayout(self.vbox_recover)
        self.textchanged = textchanged

        self.secrets_recover = QScrollArea()
        self.scroll_area_widget_contents2 = QWidget()
        self.secrets_recover.setWidget(self.scroll_area_widget_contents2)
        self.secrets_recover.setWidgetResizable(True)
        self.vbox_recover_secrets = QVBoxLayout()
        self.scroll_area_widget_contents2.setLayout(self.vbox_recover_secrets)

        self.vbox_recover.addWidget(self.secrets_recover)

        self.secrets_recover_list = []
        self.vbox_window.addWidget(self.box_recover)

        self.on_required_change()

    def validate(self):
        """check if the parameters are valid"""
        for secret in self.secrets_recover_list:
            sec, _ = secret.get_secret(1)
            #            if not is_b58_string(sec, size=28) and not is_b58_string(sec, size=30):
            if not is_b58_string(sec, size=28):
                return False
            sec, _ = secret.get_secret(2)
            #            if not is_b58_string(sec, size=14) and not is_b58_string(sec, size=30):
            if not is_b58_string(sec, size=14):
                return False
        return True

    def get_secrets(self):
        """recompute the secret 1 and secret 2 from the shamir shares and return the 2 solo secrets"""
        shares1 = []
        shares2 = []
        for secret in self.secrets_recover_list:
            sec, numi = secret.get_secret(1)
            if len(sec) == 30 and verify_solo_check(sec) is False:
                wrong_secret(1, numi)
                return None, None
            shares1.append((int(numi), sec))
            sec, numi = secret.get_secret(2)
            if len(sec) == 30 and verify_solo_check(sec) is False:
                wrong_secret(2, numi)
                return None, None
            shares2.append((int(numi), sec))
        s1 = secret1_reconstruct_base58(shares1)
        s2 = secret2_reconstruct_base58(shares2)
        return s1, s2

    def on_required_change(self):
        """Automatically adapt the layout depending on the number of required secrets"""
        for i in range(len(self.secrets_recover_list)):
            self.vbox_recover_secrets.removeWidget(
                self.secrets_recover_list[i])
            self.secrets_recover_list[i].deleteLater()

        number_required = 0
        try:
            number_required = int(self.require.text())

        except ValueError:
            pass

        self.secrets_recover_list = []
        for i in range(0, number_required):
            secretWidget = SoloProSecret(self)
            self.secrets_recover_list.append(secretWidget)
        for i in range(len(self.secrets_recover_list)):
            self.vbox_recover_secrets.addWidget(self.secrets_recover_list[i])
Ejemplo n.º 51
0
class Orders(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def closeEvent(self, event):
        if self.Timer:
            self.Timer.cancel()
        event.accept()

    def initUI(self):
        self.setGeometry(200, 150, 500, 500)
        self.setWindowTitle('Заказ в Ресторане')

        self.IsMenuLoaded = False

        self.DescriptionLabel = QPlainTextEdit(
            '   Программа оформления заказов в ресторане\n\n\n      Проект для Яндекс.Лицея по теме PyQt5\n\n\n                         Холяна Тимофея'
        )
        self.DescriptionLabel.setReadOnly(True)

        self.Help1 = QLabel('Укажите путь до базы данных')

        self.PathToDB = QLineEdit()

        self.OpenDBFile = QPushButton('...')
        self.OpenDBFile.clicked.connect(self.on_select_file)

        self.StartBtn = QPushButton('Старт')
        self.StartBtn.clicked.connect(self.on_start)

        self.OpenFileLayout = QHBoxLayout()
        self.OpenFileLayout.addWidget(self.PathToDB)
        self.OpenFileLayout.addWidget(self.OpenDBFile)

        self.FirstScreen = QVBoxLayout()
        self.FirstScreen.addWidget(self.DescriptionLabel,
                                   alignment=Qt.AlignCenter)
        self.FirstScreen.addWidget(self.Help1, alignment=Qt.AlignCenter)
        self.FirstScreen.addLayout(self.OpenFileLayout)
        self.FirstScreen.addWidget(self.StartBtn, alignment=Qt.AlignCenter)
        self.FirstScreen.addStretch(1)  # Стартовый экран

        self.DateTime = QLineEdit()
        self.DateTime.setReadOnly(True)  # Показываем время

        self.ordernum = QLineEdit()
        self.ordernum.setReadOnly(True)  # Номер заказа

        self.Header1 = QHBoxLayout()
        self.Header1.addWidget(self.DateTime,
                               alignment=Qt.AlignLeft | Qt.AlignTop)
        self.Header1.addWidget(
            self.ordernum, alignment=Qt.AlignRight
            | Qt.AlignTop)  # Эти два виджета центтрируем по верхним углам

        self.SaveOrderBtn = QPushButton('Оформить заказ')
        self.SaveOrderBtn.clicked.connect(self.get_receipt)

        self.StatsBtn = QPushButton('Отчёт')
        self.StatsBtn.clicked.connect(self.get_stats)

        self.MenuLayout = QGridLayout()  # будем распологать элементы сеткой

        self.MenuForm = QWidget()
        self.MenuForm.setLayout(self.MenuLayout)

        self.Menu1 = QScrollArea()
        self.Menu1.setWidget(self.MenuForm)
        self.Menu1.setWidgetResizable(True)  # Добавим возможность перемотки

        self.Footer1 = QHBoxLayout()
        self.Footer1.addWidget(self.SaveOrderBtn,
                               alignment=Qt.AlignCenter | Qt.AlignBottom)
        self.Footer1.addWidget(self.StatsBtn,
                               alignment=Qt.AlignCenter | Qt.AlignBottom)

        self.Help2 = QLabel('Сумма заказа: ')

        self.TotalMoney = QLineEdit()
        self.TotalMoney.setReadOnly(True)
        self.TotalMoney.setFixedWidth(200)

        self.Footer2 = QHBoxLayout()
        self.Footer2.addWidget(self.Help2,
                               alignment=Qt.AlignLeft | Qt.AlignCenter)
        self.Footer2.addWidget(self.TotalMoney,
                               alignment=Qt.AlignLeft | Qt.AlignBottom)
        self.Footer2.addStretch(1)

        self.MainScreen = QVBoxLayout()
        self.MainScreen.addLayout(self.Header1)
        self.MainScreen.addWidget(self.Menu1, stretch=1)
        self.MainScreen.addLayout(self.Footer2)
        self.MainScreen.addLayout(
            self.Footer1)  # Добавляем на основной экран нужные виджеты

        self.Notification = QLabel('Заказ прошёл успешно')

        self.Receipt = QPlainTextEdit()
        self.Receipt.setReadOnly(True)

        self.Back1 = QPushButton('Назад')
        self.Back1.clicked.connect(self.start_main)

        self.OrderScreen = QVBoxLayout()
        self.OrderScreen.addWidget(self.Notification,
                                   alignment=Qt.AlignCenter | Qt.AlignTop)
        self.OrderScreen.addWidget(self.Receipt, stretch=1)
        self.OrderScreen.addWidget(self.Back1,
                                   alignment=Qt.AlignCenter
                                   | Qt.AlignBottom)  # Создали экран с чеком

        self.Stats = QPlainTextEdit()
        self.Stats.setReadOnly(True)

        self.Back2 = QPushButton('Назад')
        self.Back2.clicked.connect(self.back_to_main)

        self.StatsScreen = QVBoxLayout()
        self.StatsScreen.addWidget(self.Stats, stretch=1)
        self.StatsScreen.addWidget(
            self.Back2, alignment=Qt.AlignCenter
            | Qt.AlignBottom)  # Создали экран со статистикой

        self.StLayout = QStackedLayout(
        )  # Виджет для отображения нескольких экранов в одном окне

        self.Frame1 = QFrame(self)
        self.Frame1.setLayout(self.FirstScreen)  # Собственно первый экран

        self.StLayout.addWidget(self.Frame1)

        self.setLayout(self.StLayout)

    def on_select_file(self):
        FileName, _ = QFileDialog.getOpenFileName(self, 'Открыть базу данных',
                                                  None, '*.db')
        if FileName:
            self.PathToDB.setText(
                FileName)  # Чтобы выбрать и подключить базу данных

    def get_filename(self):
        return self.PathToDB.text()

    def on_start(self):
        FileName = self.get_filename()
        if FileName:
            try:
                con = sqlite3.connect(FileName)
                cur = con.cursor()
                self.meals = cur.execute(
                    """SELECT id, name, price FROM meals""").fetchall()
                if len(self.meals) == 0:
                    msg = QErrorMessage(self)
                    msg.showMessage('В базе данных нет продуктов')
                con.close()
                self.start_main()
            except Exception as e:
                msg = QErrorMessage(self)
                msg.showMessage('Неверный путь до базы данных. ' + str(e))
        else:
            msg = QErrorMessage(self)
            msg.showMessage(
                'Не указан путь до базы данных'
            )  # Отображение основного экрана или увеномление об ошибке

    def GetMaxOrdersNum(self):
        con = sqlite3.connect(self.get_filename())
        cur = con.cursor()
        maxId = cur.execute("""SELECT MAX(id) FROM orders""").fetchone()
        con.close()
        if maxId[0] is None:
            return 0
        return maxId[0]  # Нужная функция

    def SaveOrder(self):
        con = sqlite3.connect(self.get_filename())
        cur = con.cursor()
        cur.execute("""INSERT INTO orders (date) VALUES (date('now'))""")
        self.OrderId = cur.lastrowid
        for i in self.choices:
            if i.isChecked() and int(
                    self.numbers[self.choices.index(i)].text()) != 0:
                cur.execute(
                    """INSERT INTO ordered (id_order,id_meal,count) VALUES (?,?,?)""",
                    (self.OrderId, self.mealsid[self.choices.index(i)],
                     int(self.numbers[self.choices.index(i)].text())))
        con.commit()
        con.close()  # Сохраняем заказ в базу данных

    def getStatsDaily(self):
        con = sqlite3.connect(self.get_filename())
        cur = con.cursor()
        result = cur.execute("""SELECT id_meal, count FROM ordered 
                                    WHERE(id_order in (SELECT id FROM orders WHERE date=date('now')))"""
                             ).fetchall()
        con.close()
        g = []
        for i in self.mealsid:
            s = 0
            for j in result:
                if j[0] == i:
                    s += j[1]
            if s != 0:
                g.append((i, s))
        return g

    def getTotalSell(self):
        con = sqlite3.connect(self.get_filename())
        cur = con.cursor()
        result = cur.execute("""SELECT id_meal, count FROM ordered 
                                    WHERE(id_order in (SELECT id FROM orders WHERE date=date('now')))"""
                             ).fetchall()
        con.close()
        s = 0.0
        for i in result:
            ind = self.mealsid.index(i[0])
            s += self.prices[ind] * i[1]
        return s  # методы, подщитывающие данные для отчёта

    def updateTime(self):
        now = datetime.now()
        self.DateTime.setText(
            now.strftime("%d.%m.%Y %H:%M:%S"))  # Показать время

    def start_main(self):
        self.ordernum.setText('Заказ №' + str(self.GetMaxOrdersNum() + 1))
        self.TotalMoney.setText('0.0 рублей')
        if not self.IsMenuLoaded:
            self.timer = perpetualTimer(1, self.updateTime)
            self.timer.start()
            self.updateTime()
            self.mealsid = []
            self.prices = []
            self.choices = []
            self.money = []
            self.counting = []
            self.numbers = []
            for i, row in enumerate(self.meals):
                self.mealsid.append(row[0])
                self.prices.append(row[2])
                qc = QCheckBox(row[1])
                qc.clicked.connect(self.updateTotalMoney)
                self.choices.append(qc)
                self.MenuLayout.addWidget(qc, i, 1)
                qm = QLabel(str(self.prices[i]) + ' р.')
                self.MenuLayout.addWidget(qm, i, 2)
                btn, btn2 = QPushButton('-'), QPushButton('+')
                self.MenuLayout.addWidget(btn, i, 3)
                self.MenuLayout.addWidget(btn2, i, 4)
                btn.setFixedWidth(40)
                btn2.setFixedWidth(40)
                btn.clicked.connect(self.less)
                btn2.clicked.connect(self.more)
                self.counting.append(btn)
                self.counting.append(btn2)
                qn = QLabel('0')
                self.numbers.append(qn)
                self.MenuLayout.addWidget(qn, i, 5)

            self.MenuLayout.setColumnStretch(5, 1)
            self.MenuLayout.setRowStretch(len(self.meals), 1)
            self.Frame2 = QFrame(self)
            self.Frame2.setLayout(self.MainScreen)
            self.StLayout.addWidget(self.Frame2)
            self.Frame3 = QFrame(self)
            self.Frame3.setLayout(self.OrderScreen)
            self.StLayout.addWidget(self.Frame3)
            self.Frame4 = QFrame(self)
            self.Frame4.setLayout(self.StatsScreen)
            self.StLayout.addWidget(self.Frame4)
            self.IsMenuLoaded = True
        else:
            # обнулить все значения
            for i in self.numbers:
                i.setText('0')
            for i in self.choices:
                i.setChecked(False)
        self.StLayout.setCurrentIndex(
            1)  # Будем загружать основной экран и чистить его когда надо

    def back_to_main(self):
        self.StLayout.setCurrentIndex(1)  # К кнопке 'назад'

    def get_receipt(self):
        self.start_receipt()

    def start_receipt(self):
        try:
            if sum([
                    int(self.numbers[self.choices.index(i)].text())
                    for i in self.choices if i.isChecked()
            ]) == 0:
                msg = QErrorMessage(self)
                msg.showMessage('Не выбрано ни одного блюда.')
                return
            self.SaveOrder()
            self.Receipt.setPlainText(self.PrintReciept())
            self.StLayout.setCurrentIndex(2)
        except Exception as e:
            msg = QErrorMessage(self)
            msg.showMessage('Ошибка: ' +
                            str(e))  # Загружаем чек при соблюдённых условиях

    def PrintReciept(self):
        ordered = [
            i.text() + ' (*' + self.numbers[self.choices.index(i)].text() +
            ')' + ' - ' + str(
                int(self.numbers[self.choices.index(i)].text()) *
                self.prices[self.choices.index(i)]) + ' рублей'
            for i in self.choices if i.isChecked()
            and self.numbers[self.choices.index(i)].text() != '0'
        ]
        strReciept = ''
        strReciept = strReciept + '------------------------------------------' + '\n'

        now = datetime.now()
        strReciept = strReciept + 'Заказ №' + str(
            self.OrderId) + '  ' + now.strftime("%d.%m.%Y %H:%M:%S")
        strReciept = strReciept + '\n' + '------------------------------------------' + '\n'
        strReciept = strReciept + str('\n'.join(ordered))
        strReciept = strReciept + '\n' + '------------------------------------------' + '\n'
        strReciept = strReciept + 'Всего - ' + str(
            self.calculateTotal()) + ' рублей'
        strReciept = strReciept + '\n' + '------------------------------------------' + '\n'
        return strReciept  # Печатаем чек

    def get_stats(self):
        self.start_stats()

    def start_stats(self):
        try:
            self.Stats.setPlainText(self.PrintStats())
            self.StLayout.setCurrentIndex(3)
        except Exception as e:
            msg = QErrorMessage(self)
            msg.showMessage('Ошибка: ' +
                            str(e))  # Также как с чеком, формулируем отчёт

    def PrintStats(self):
        StatsDaily = self.getStatsDaily()
        TotalSell = self.getTotalSell()
        now = datetime.now()
        strStats = ''
        strStats += 'Отчёт за ' + now.strftime("%d.%m.%Y")
        strStats += '\n\nПродано за день:\n'
        for i in StatsDaily:
            mealnum = self.mealsid.index(i[0])
            strStats += '- ' + self.choices[mealnum].text() + ': ' + str(
                i[1]) + ' шт.\n'
        strStats += 'Всего продано товаров на сумму ' + str(
            TotalSell) + ' рублей.'
        return strStats  # И печатаем его

    def less(self):
        number = self.numbers[self.counting.index(self.sender()) // 2]
        if number.text() != '0':
            number.setText(str(int(number.text()) - 1))
        self.updateTotalMoney()

    def more(self):
        number = self.numbers[self.counting.index(self.sender()) // 2]
        number.setText(str(int(number.text()) + 1))
        self.updateTotalMoney(
        )  # Для работы кнопок, формирующих количество одинаковых блюд в заказе

    def updateTotalMoney(self):
        self.TotalMoney.setText(str(self.calculateTotal()) + ' рублей')

    def calculateTotal(self):
        return float(
            sum([
                float(self.numbers[self.choices.index(i)].text()) *
                self.prices[self.choices.index(i)] for i in self.choices
                if i.isChecked()
            ]))
Ejemplo n.º 52
0
class CVImageWidget(QWidget):

    image = None

    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.setLayout(QVBoxLayout())
        self.layout().setContentsMargins(0, 0, 0, 0)

        self.scrollArea = QScrollArea(self)
        self.scrollArea.setVisible(False)

        self.imageLabel = QLabel(self)
        self.imageLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        self.imageLabel.setScaledContents(True)

        self.scrollArea.setWidget(self.imageLabel)
        self.layout().addWidget(self.scrollArea)

        self.setFocusPolicy(Qt.ClickFocus)
        self.setFocus(Qt.MouseFocusReason)

    def setImage(self, cvimage):
        s = cvimage.shape
        if len(s) == 3:
            height, width, colors = cvimage.shape
            bytesPerLine = 3 * width
            img_format = QImage.Format_RGB888
        else:
            height, width = cvimage.shape
            colors = 0
            bytesPerLine = width
            img_format = QImage.Format_Grayscale8

        self.image = QImage(cvimage.data, width, height, bytesPerLine,
                            img_format)
        self.scaleFactor = 1
        self.imageLabel.setPixmap(QPixmap.fromImage(self.image))
        self.scrollArea.setVisible(True)
        self.imageLabel.adjustSize()
        self.update()

    def scaleImage(self, factor):
        print('scaleFactor = %f' % self.scaleFactor)
        if (self.scaleFactor > 3 and factor > 1) or (self.scaleFactor < 0.1
                                                     and factor < 1):
            return

        self.scaleFactor *= factor
        self.imageLabel.resize(self.scaleFactor *
                               self.imageLabel.pixmap().size())

        self.adjustScrollBar(self.scrollArea.horizontalScrollBar(), factor)
        self.adjustScrollBar(self.scrollArea.verticalScrollBar(), factor)

    def adjustScrollBar(self, scrollbar, factor):
        scrollbar.setValue(
            int(factor * scrollbar.value() +
                ((factor - 1) * scrollbar.pageStep() / 2)))

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Equal and event.modifiers(
        ) == Qt.ControlModifier:
            self.scaleImage(1.2)
        elif event.key() == Qt.Key_Minus and event.modifiers(
        ) == Qt.ControlModifier:
            self.scaleImage(0.8)

        QWidget.keyPressEvent(self, event)

    def contextMenuEvent(self, event):
        menu = QMenu(self)
        full_action = QAction('100 %', self)
        full_action.triggered.connect(self.normalSize)
        menu.addAction(full_action)

        width_action = QAction('Fit width', self)
        width_action.triggered.connect(lambda: self.fit(Qt.Horizontal))
        menu.addAction(width_action)

        height_action = QAction('Fit height', self)
        height_action.triggered.connect(lambda: self.fit(Qt.Vertical))
        menu.addAction(height_action)

        save_action = QAction('Save', self)
        save_action.triggered.connect(self.saveImage)
        menu.addAction(save_action)

        menu.exec(self.mapToGlobal(event.pos()))

    def normalSize(self):
        self.scaleFactor = 1
        self.scaleImage(1)

    def fit(self, orientation):

        imsize = self.imageLabel.pixmap().size()
        sasize = self.scrollArea.size()

        hfactor = sasize.width() / imsize.width()
        vfactor = sasize.height() / imsize.height()
        factor = hfactor if orientation == Qt.Horizontal else vfactor

        self.scaleFactor = 1
        self.scaleImage(factor)

    def saveImage(self):
        filename, _ = QFileDialog.getSaveFileName()

        if filename:
            self.image.save(filename)
Ejemplo n.º 53
0
    def initUI(self):
        # 读取配置文件
        global config_dic
        global twolineflag
        try:
            with open('config.json', 'r') as load_f:
                config_dic = json.load(load_f)
        except:
            config_dic = config_dic
            QMessageBox.information(
                self,  # 使用infomation信息框
                "注意",
                "未找到配置文件 请手动选择")
            self.read_json()
            # 初始化连接
        self.IPbox = QLineEdit()
        #self.IPbox.setText("192.168.201.129")
        self.re_num = 1
        self.usernamebox = QLineEdit()
        self.ethbox = QLineEdit()
        self.passwordbox = QLineEdit()
        self.connect_button = QPushButton("测试连接")
        self.update_button = QPushButton("更新配置")
        hbox1 = QHBoxLayout()
        hbox1.addWidget(QLabel("被测试IP:"))
        hbox1.addWidget(self.IPbox)
        hbox1.addWidget(self.connect_button)
        hbox1.addWidget(QLabel("      "))
        hbox1.addWidget(QLabel("本机用户名:"))
        hbox1.addWidget(self.usernamebox)
        hbox1.addWidget(QLabel("本机密码:"))
        hbox1.addWidget(self.passwordbox)
        hbox1.addWidget(QLabel("网口号:"))
        hbox1.addWidget(self.ethbox)

        hbox1.addWidget(self.update_button)

        self.connect_button.clicked.connect(self.connect)
        self.update_button.clicked.connect(self.read_json)

        # 中间

        self.topFiller = QWidget()
        self.topFiller.setMinimumSize(2500, 2000)  #######设置滚动条的尺寸
        self.tab = QTabWidget()
        for test_type in config_dic.keys():
            send_list[test_type] = []
            tab_name.append(test_type)

            self.tab.test_type = Checkboxlist(test_type)
            l = int(len(test_type) / 2)
            s = test_type[0:l] + '\n' * twolineflag + test_type[l:]
            self.tab.addTab(self.tab.test_type, s)
        # tab.tabBar().setFixedHeight(48)
        hbox2 = QHBoxLayout(self.topFiller)
        hbox2.addWidget(self.tab)
        #hbox2.addWidget(self.scroll)
        self.scroll = QScrollArea()
        self.scroll.setWidget(self.topFiller)

        # 辅助功能
        hbox3 = QHBoxLayout()
        hbox4 = QHBoxLayout()
        self.re_timebox = QSlider(Qt.Horizontal, self)
        self.re_timebox.setMinimum(1)
        self.re_timebox.setMaximum(1000)
        self.re_timebox.valueChanged[int].connect(self.changeValue)
        self.num = QLabel("1")
        self.fullspeed = QCheckBox("全速发送")
        hbox3.addWidget(self.fullspeed)  # -R

        hbox4.addWidget(QLabel("  重复次数:"))
        hbox4.addWidget(self.num)
        hbox4.addWidget(self.re_timebox)

        hbox3.addWidget(QLabel("  最大发包数量:"))
        self.maxpacknumbox = QLineEdit()  # -L
        hbox3.addWidget(self.maxpacknumbox)
        hbox3.addWidget(QLabel("  每秒发送报文数:"))
        self.packpsbox = QLineEdit()  # -p
        hbox3.addWidget(self.packpsbox)
        '''hbox3.addWidget(QLabel("  指定MTU:"))
        self.MTUbox = QLineEdit()  # -t
        hbox3.addWidget(self.MTUbox)'''

        hbox3.addWidget(QLabel("发包速度/Mbps:"))
        self.Mbpsbox = QLineEdit()
        hbox3.addWidget(self.Mbpsbox)

        # 开始测试
        self.start_button = QPushButton("开始发送数据包")
        self.start_button.clicked.connect(self.start_test)
        self.stop_button = QPushButton("停止发送数据包")
        self.stop_button.clicked.connect(self.stop_test)
        hbox5 = QHBoxLayout()
        hbox5.addWidget(self.start_button)
        hbox5.addWidget(self.stop_button)
        #        hbox5.addWidget(QLabel("                            time:"))
        #        self.timebox = QLineEdit()
        #        hbox5.addWidget(self.timebox)
        # 显示输出结果
        self.resultbox = QTextBrowser()

        vbox = QVBoxLayout()
        vbox.addLayout(hbox1)
        vbox.addWidget(QLabel("选择测试模式:"))

        #vbox.addLayout(hbox2)
        vbox.addWidget(self.scroll)
        vbox.addWidget(QLabel("可选项:"))
        vbox.addLayout(hbox3)
        vbox.addLayout(hbox4)

        vbox.addLayout(hbox5)
        vbox.addWidget(QLabel("状态提示信息:"))
        vbox.addWidget(self.resultbox)
        self.setLayout(vbox)
        # self.setGeometry(300, 300, 290, 150)
        self.setWindowTitle('tcpreplay_gui')
        self.show()
Ejemplo n.º 54
0
    def __init__(self):
        print("__init__")
        lists.create()
        favorites.create()

        widget_list = []
        favorites_list = []
        self.lock = passs.update("false", "true")
        check1 = lists.viewall()
        check2 = favorites.viewall()
        password = (passs.viewall())[0][1]
        for i in check1:
            a = []
            for j in i:
                if (isinstance(j, str)):
                    a.append(j)
            widget_list.append(a)

        for i in check2:
            a = []
            for j in i:
                if (isinstance(j, str)):
                    a.append(j)
            favorites_list.append(a)

        for i in widget_list:
            if (i[4] not in tag_list):
                tag_list.append(i[4])

        super(base_1, self).__init__()
        self.setupUi(self)
        self.account = QWidget()
        self.accountLayout = QVBoxLayout()
        for i in reversed(range(self.accountLayout.count())):
            self.accountLayout.itemAt(i).widget().setParent(None)
        self.widgets = []
        for info in widget_list:
            item = AccountWidget(info[0], info[1], info[2], info[3], info[4],
                                 info[5])
            self.accountLayout.addWidget(item)
            self.widgets.append(item)
        self.account.setLayout(self.accountLayout)

        self.scroll = QScrollArea()
        self.scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.scroll.setWidgetResizable(True)
        self.scroll.setWidget(self.account)

        self.scroll2 = QScrollArea()
        self.scroll2.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.scroll2.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.scroll2.setWidgetResizable(True)

        self.scroll3 = QScrollArea()
        self.scroll3.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.scroll3.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.scroll3.setWidgetResizable(True)

        self.searchbar = self.SearchLine
        self.searchbar.textChanged.connect(self.update)

        container = self.SearchReturn
        containerLayout = QVBoxLayout()
        containerLayout.addWidget(self.scroll)

        container.setLayout(containerLayout)
        site_names = []
        for i in widget_list:
            site_names.append(i[0])

        self.completer = QCompleter(site_names)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.searchbar.setCompleter(self.completer)

        self.AddButton.clicked.connect(self.AddButtonClicked)
        self.favorites = QWidget()
        self.favoritesLayout = QVBoxLayout()
        for i in reversed(range(self.favoritesLayout.count())):
            self.favoritesLayout.itemAt(i).widget().setParent(None)
        self.favorites_widget = []
        for info in favorites_list:
            item = FavoritesWidget(info[0], info[1], info[2], info[3], info[4],
                                   info[5])
            self.favoritesLayout.addWidget(item)
            self.favorites_widget.append(item)

        self.favorites.setLayout(self.favoritesLayout)
        self.scroll2.setWidget(self.favorites)
        container2 = self.Favorites
        container2Layout = QVBoxLayout()
        container2Layout.addWidget(self.scroll2)

        container2.setLayout(container2Layout)

        self.HelpButton.clicked.connect(self.HelpButtonClicked)

        self.tray_icon = QSystemTrayIcon(self)
        self.tray_icon.setIcon(self.style().standardIcon(
            QStyle.SP_ComputerIcon))
        self.tray_icon.activated.connect(self.showing)
        '''
            Define and add steps to work with the system tray icon
            show - show window
            hide - hide window
            exit - exit from application
        '''
        show_action = QAction("창 보이기", self)
        quit_action = QAction("프로그램 종료", self)
        hide_action = QAction("창 숨기기", self)
        show_action.triggered.connect(self.show)
        hide_action.triggered.connect(self.hide)
        quit_action.triggered.connect(self.quiting)
        tray_menu = QMenu()
        tray_menu.addAction(show_action)
        tray_menu.addAction(hide_action)
        tray_menu.addAction(quit_action)
        self.tray_icon.setContextMenu(tray_menu)
        self.tray_icon.show()
        self.resetButton.clicked.connect(self.reset)

        self.tags = QWidget()
        self.tagsLayout = QVBoxLayout()
        for i in reversed(range(self.tagsLayout.count())):
            self.tagsLayout.itemAt(i).widget().setParent(None)
        self.tags_widget = []
        for info in tag_list:
            item = Tag(info)
            self.tagsLayout.addWidget(item)
            self.tags_widget.append(item)
        self.tags.setLayout(self.tagsLayout)
        self.scroll3.setWidget(self.tags)
        container3 = self.TagWidget
        container3Layout = QVBoxLayout()
        container3Layout.addWidget(self.scroll3)

        container3.setLayout(container3Layout)

        self.lockButton.clicked.connect(self.LockButtonClicked)
        self.changePassword.clicked.connect(self.ChangeButtonClicked)
        self.setFixedSize(1000, 650)
Ejemplo n.º 55
0
class Window(QMainWindow):
    def __init__(self):
        super().__init__()

        self.clipboard_text = QApplication.clipboard().text()
        self.volume = 100
        self.clippers = []

        self.init_main_window()
        self.init_elements()
        self.init_events()

        self.load_data()

    def load_data(self):
        if not os.path.isfile("data.pkl"):
            return False

        with open("data.pkl", "rb") as read_data:
            window_clippers = pickle.load(read_data)

            for clipper_id, pair in window_clippers.items():
                label_text = pair["text"]
                titlebar_text = pair["title"]

                self.add_clipper(0, label_text, titlebar_text, clipper_id)

    # GUI Initialization
    def init_main_window(self):
        self.setGeometry(screen_width - window_width,
                         (screen_height // 2) - (window_height // 2),
                         window_width, window_height)
        self.setFixedSize(self.size())
        self.setWindowTitle("PyClipper")
        self.setWindowIcon(QIcon("images/favicon.png"))
        self.setWindowFlags(Qt.WindowStaysOnTopHint)

    def init_elements(self):
        # Clipper Button Area
        self.add_clipper_button = QPushButton('Add clipper', self)
        self.add_clipper_button.resize(100, 32)

        self.add_clipper_button_frame, self.add_clipper_button_layout = WidgetUtils.add_widget_with_alignment(
            self, self.add_clipper_button, QHBoxLayout, Qt.AlignCenter)

        # Clipper Scroll Area
        self.clipper_scroll_area = QScrollArea(self)
        self.clipper_scroll_area.resize(self.width(), 472)
        self.clipper_scroll_area.move(0, 42)
        self.clipper_scroll_area.setWidgetResizable(True)

        self.scroll_area_layout = QVBoxLayout(self.clipper_scroll_area)

        self.scroll_widget = QWidget(self)
        self.scroll_widget.setLayout(self.scroll_area_layout)

        self.clipper_scroll_area.setWidget(self.scroll_widget)

        # Sound Setting Elements
        self.sound_groupbox = QGroupBox("Sound Settings", self)
        self.sound_groupbox.resize(330, 60)

        self.sound_groupbox_frame, self.sound_groupbox_layout = WidgetUtils.add_widget_with_alignment(
            self, self.sound_groupbox, QHBoxLayout, False)
        self.sound_groupbox_frame.resize(400, 75)
        self.sound_groupbox_frame.move(0, 520)

        self.sound_checkbox = QCheckBox(self)
        self.sound_checkbox.resize(13, 13)
        self.sound_checkbox.move(100, 520)
        self.sound_checkbox.toggle()

        self.sound_scrollbar = QSlider(Qt.Horizontal, self.sound_groupbox)
        self.sound_scrollbar.resize(300, 20)
        self.sound_scrollbar.move(22, 30)
        self.sound_scrollbar.setMaximum(100)
        self.sound_scrollbar.setValue(100)

        self.sound_scrollbar_value = QLabel(self.sound_groupbox)
        self.sound_scrollbar_value.setText("100%")
        self.sound_scrollbar_value.setAlignment(Qt.AlignCenter)

        text_width = WidgetUtils.get_label_size(self.sound_scrollbar_value)[0]
        self.sound_scrollbar_value.move(
            WidgetUtils.horizontal_align_center(self.sound_scrollbar,
                                                text_width), 0)

    def init_events(self):
        # Events for application
        self.destroyed.connect(self._on_destroyed)

        # Events for widgets on applicaton
        self.add_clipper_button.clicked.connect(self.add_clipper_pressed)
        self.sound_checkbox.stateChanged.connect(self.sound_state_changed)
        self.sound_scrollbar.valueChanged.connect(self.slider_value_changed)
        self.sound_scrollbar.sliderReleased.connect(self.slider_released)

        # Global events
        QApplication.clipboard().dataChanged.connect(self.clipboard_changed)

    # Event functions
    def slider_value_changed(self):
        self.sound_scrollbar_value.setText("{}%".format(
            self.sound_scrollbar.value()))

    def slider_released(self):
        self.set_clipper_volume(self.sound_scrollbar.value())

    def sound_state_changed(self):
        state = self.sound_checkbox.checkState() == 2
        self.sound_groupbox.setEnabled(state)

    def clipboard_changed(self, index=0):
        """
        This method executes when the actual string in clipboard changes.
        Furthermore plays a little clipsound using the SoundHandler by PyQT.
        """
        if self.clipboard_text != QApplication.clipboard().text():
            self.clipboard_text = QApplication.clipboard().text()

            if self.sound_groupbox.isEnabled():
                SoundHandler.play_clip_sound(self.volume)

            self.add_clipper(index, self.clipboard_text)

    def add_clipper_pressed(self, index=0):
        """
        This method executes when the "Add clipper" button is pressed.
        It adds a new Clipper on index 0 to the vertical layout in the scroll area.
        """
        self.add_clipper(index)

    def add_clipper(self, index, text="", title="", random_id=None):
        clip = Clipper(self)
        self.scroll_area_layout.insertWidget(index, clip)

        if len(text) > 0:
            clip.text = text

        if len(title) > 0:
            clip.title = title

        # Create new random id, if not a specific id is given
        if random_id is None:
            random_id = random.randint(100000, 999999)

        # Reroll id if it exists already
        while (window_clippers.get(random_id)):
            random_id = random.randint(100000, 999999)

        clip.id = random_id
        window_clippers[clip.id] = {"title": clip.title, "text": clip.text}

        self.clippers.append(clip)
        self.resize_window_clippers()

    def resize_window_clippers(self):
        for clip in self.clippers:
            if len(window_clippers) > 2:
                clip.setFixedWidth(314)
            else:
                clip.setFixedWidth(330)

    def set_clipper_volume(self, volume):
        self.volume = volume

    @staticmethod
    def _on_destroyed(self):
        """
        This method executes when the window is destroyed.
        Saves the window_clippers in a file, so that it can be loaded afterwards.
        """
        with open("data.pkl", "bw") as write_data:
            pickle.dump(window_clippers, write_data)
Ejemplo n.º 56
0
class ImageViewerUi(QMainWindow):
    """View Gui"""
    def __init__(self):
        """View Initializer"""
        super().__init__()
        #Some main properties of the WindowsError
        self.setWindowTitle('ImageViewer')

        #Set central widget and the general layout
        self.generalLayout = QHBoxLayout()
        self._centralWidget = QScrollArea()
        self.setCentralWidget(self._centralWidget)
        self._centralWidget.setLayout(self.generalLayout)
        self._centralWidget.setMinimumSize(2000, 800)
        """Don't forget to actually create a display"""
        self._createDisplay()
        self._createMenuBar()
        self._createViewList()

    def _createMenuBar(self):
        """Create a menubar"""
        menuBar = self.menuBar()
        self.menuBar = QMenuBar()
        fileMenu = menuBar.addMenu('File')
        self.generalLayout.addWidget(self.menuBar)
        """create menu items"""
        openAct = QAction('Open Images', self)
        openAct.triggered.connect(self.openImages)
        fileMenu.addAction(openAct)

    def _createViewList(self):
        #create file view list
        self.ViewList_Box = QtWidgets.QGroupBox('Open Images')
        self.ViewList_Box.setMinimumSize(400, 200)
        self.ViewList_Layout = QtWidgets.QFormLayout()
        self.ViewList_RawList = QtWidgets.QListView()
        self.ViewList_Items = QtGui.QStandardItemModel(self.ViewList_RawList)

        self.ViewList_Box.setLayout(self.ViewList_Layout)

        self.ViewList_Layout.addWidget(self.ViewList_RawList)
        self.ViewList_Layout.setSpacing(2)
        self.ViewList_Layout.setContentsMargins(2, 2, 2, 2)
        self.ViewList_RawList.setModel(self.ViewList_Items)

        self.generalLayout.addWidget(self.ViewList_Box)

        self.ViewList_Items.itemChanged.connect(self.updateDisplay)

    def updateDisplay(self, image):
        if type(image) is QPixmap:
            pixmap = image
        else:
            raise RuntimeError(
                "ImageViewer.setImage: Argument must be a QImage or QPixmap.")
        if self.hasImage():
            self._pixmapHandle.setPixmap(pixmap)
        else:
            self._pixmapHandle = self.scene.addPixmap(pixmap)
        self.setSceneRect(QRectF(
            pixmap.rect()))  # Set scene size to image size.
        self._createDisplay()

    def _createDisplay(self):
        #Create display widget
        self.display = QLabel()
        #set display properties
        self.display.setAlignment(Qt.AlignCenter)
        self.display.setMinimumSize(600, 1000)

        #add this display to the general layout
        self.generalLayout.addWidget(self.display)

    def openImages(self):
        fileNames = QFileDialog.getOpenFileNames(
            self, self.tr("Select image(s) to open"))
        for fileName in fileNames[0]:
            self.importImageWrapper(fileName)

    def importImageWrapper(self, fileName):
        image = QPixmap(fileName)
        file = QtGui.QStandardItem(fileName)
        file.setCheckable(True)
        self.ViewList_Items.appendRow(file)
        self.display.setPixmap(image)
        self.resize(image.size())
        self.adjustSize()
Ejemplo n.º 57
0
    def __init__(self, title, x, y, width, height):
        super().__init__()
        '''
            Menu bar code for getting the menu bar to
            have file menus
        '''
        self.statusBar().showMessage("Waiting to start...")
        self.menuBarObject = self.menuBar()
        self.actionMenu = self.menuBarObject.addMenu("&File")
        '''
            We add an about menu so that you can find all
            of the keyboard shortcuts in case you forget.
        '''
        self.aboutMenu = self.menuBarObject.addMenu("&About")
        self.helpAction = QAction("&Help")
        self.helpAction.setShortcut("ctrl+h")
        self.helpAction.triggered.connect(self.helpFunc)
        self.aboutMenu.addAction(self.helpAction)
        '''
            We have a save mode action from the file
            menu
        '''
        self.saveModel = QAction("&Save Model")
        self.saveModel.setShortcut("ctrl+s")
        self.saveModel.triggered.connect(self.saveFunc)
        self.actionMenu.addAction(self.saveModel)
        '''
            We also have a save as action inside the
            file menu
        '''
        self.saveModelAs = QAction("&Save Model As")
        self.saveModelAs.setShortcut("ctrl+alt+s")
        self.saveModelAs.triggered.connect(self.saveAsFunc)
        self.actionMenu.addAction(self.saveModelAs)
        '''
            Adds an option menu to the status bar
        '''
        self.optionsMenu = self.menuBarObject.addMenu("&Options")
        '''
            We can toggle if the current AI is paused or not.
        '''
        self.togglePause = QAction("&Toggle Pause")
        self.togglePause.setShortcut("ctrl+p")
        self.togglePause.triggered.connect(self.pauseFunc)
        '''
            We can toggle between training and debug mode
            to see the current screen to examine the output
            that the AI will see.
        '''
        self.toggleTraining = QAction("&Toggle Training")
        self.toggleTraining.setShortcut("ctrl+t")
        self.toggleTraining.triggered.connect(self.toggleTrainingFunc)
        '''
            We can load an existing model as well from
            the file menu
        '''
        self.loadModel = QAction("&Load Model")
        self.loadModel.setShortcut("ctrl+k")
        self.loadModel.triggered.connect(self.loadModelFunc)
        '''
            This is a label to let us know what the current
            state of the AI program is.
            
            The first parameter is the paused status. Either
            PAUSED or UNPAUSED
            
            The second parameter is the current state,
            either TRAINING or DEBUG
        '''
        self.aiStateLabel = QLabel(self)
        self.aiStateText = "Current AI State: "
        self.aiStateLabel.setGeometry(0, 20, self.width(), 50)
        self.aiStateLabel.setText(self.aiStateText)
        self.aiStateLabel.show()
        '''
            This is a label that will tell us which model
            is currently loaded so we know what we're saving to.
            This is the name that gets saved to when you do
            a save command.
            
            When a new file is loaded this text is updated to reflect the
            current file that's open.
        '''
        self.currentAIModelInUse = QLabel(self)
        self.currentAIModelInUseText = "Current Loaded Model: "
        self.currentAIModelInUse.setGeometry(0, 80, self.width(), 20)
        self.currentAIModelInUse.setText(self.currentAIModelInUseText +
                                         "model.txt")
        self.currentAIModelInUse.show()
        '''
            This code just adds the submenus (actions) to the
            file menu.
        '''
        self.optionsMenu.addAction(self.togglePause)
        self.optionsMenu.addAction(self.toggleTraining)
        self.optionsMenu.addAction(self.loadModel)

        self.width = width  # Width of the window in pixels
        self.height = height  # Height pf the window in pixels
        self.title = title  # The title of the window
        self.setGeometry(x, y, self.width, self.height)
        self.setWindowTitle(
            self.title)  # Sets the title to the string specified
        '''
            It's hard to see the entire QTable if we don't put it
            inside of a QScrollArea. It will allow you to see
            the entirety of the QTable this way.
        '''
        self.qTableLabel = QLabel(self)
        self.qTableScroller = QScrollArea(self)
        self.qTableScroller.setGeometry(0, 100, self.width, self.height // 2)

        self.screenRecorderObj = mss(
        )  # A handle to the screen recording object
        self.recordingViewport = None  # The viewport that the screen will record from
        self.recordingRate = 60  # The number of times per second that we will grab a new frame from the screen

        self.currentCapture = None  # The current frame that was just captured
        self.videoFeed = QLabel(
            self)  # The video feed object drawn to the window
        self.globalTimer = QTimer(
            self)  # A global timer to keep track of when to grab a screenshot

        self.isPaused = True  # Keeps track of if the AI is paused or not currently
        self.isTraining = True  # Keeps track of if we are in debug mode or not
        self.currentAgent = None  # Keeps track of the current agent parameters
        self.currentModelFile = None  # Keeps track of the current model we have loaded
Ejemplo n.º 58
0
class Window(QMainWindow):
    '''
        :param title:
            The title of the window that will be shown in the
            top of the screen.

        :param width:
            The width of the window in pixels.

        :param height:
            The height of the window in pixels.
    '''
    def __init__(self, title, x, y, width, height):
        super().__init__()
        '''
            Menu bar code for getting the menu bar to
            have file menus
        '''
        self.statusBar().showMessage("Waiting to start...")
        self.menuBarObject = self.menuBar()
        self.actionMenu = self.menuBarObject.addMenu("&File")
        '''
            We add an about menu so that you can find all
            of the keyboard shortcuts in case you forget.
        '''
        self.aboutMenu = self.menuBarObject.addMenu("&About")
        self.helpAction = QAction("&Help")
        self.helpAction.setShortcut("ctrl+h")
        self.helpAction.triggered.connect(self.helpFunc)
        self.aboutMenu.addAction(self.helpAction)
        '''
            We have a save mode action from the file
            menu
        '''
        self.saveModel = QAction("&Save Model")
        self.saveModel.setShortcut("ctrl+s")
        self.saveModel.triggered.connect(self.saveFunc)
        self.actionMenu.addAction(self.saveModel)
        '''
            We also have a save as action inside the
            file menu
        '''
        self.saveModelAs = QAction("&Save Model As")
        self.saveModelAs.setShortcut("ctrl+alt+s")
        self.saveModelAs.triggered.connect(self.saveAsFunc)
        self.actionMenu.addAction(self.saveModelAs)
        '''
            Adds an option menu to the status bar
        '''
        self.optionsMenu = self.menuBarObject.addMenu("&Options")
        '''
            We can toggle if the current AI is paused or not.
        '''
        self.togglePause = QAction("&Toggle Pause")
        self.togglePause.setShortcut("ctrl+p")
        self.togglePause.triggered.connect(self.pauseFunc)
        '''
            We can toggle between training and debug mode
            to see the current screen to examine the output
            that the AI will see.
        '''
        self.toggleTraining = QAction("&Toggle Training")
        self.toggleTraining.setShortcut("ctrl+t")
        self.toggleTraining.triggered.connect(self.toggleTrainingFunc)
        '''
            We can load an existing model as well from
            the file menu
        '''
        self.loadModel = QAction("&Load Model")
        self.loadModel.setShortcut("ctrl+k")
        self.loadModel.triggered.connect(self.loadModelFunc)
        '''
            This is a label to let us know what the current
            state of the AI program is.
            
            The first parameter is the paused status. Either
            PAUSED or UNPAUSED
            
            The second parameter is the current state,
            either TRAINING or DEBUG
        '''
        self.aiStateLabel = QLabel(self)
        self.aiStateText = "Current AI State: "
        self.aiStateLabel.setGeometry(0, 20, self.width(), 50)
        self.aiStateLabel.setText(self.aiStateText)
        self.aiStateLabel.show()
        '''
            This is a label that will tell us which model
            is currently loaded so we know what we're saving to.
            This is the name that gets saved to when you do
            a save command.
            
            When a new file is loaded this text is updated to reflect the
            current file that's open.
        '''
        self.currentAIModelInUse = QLabel(self)
        self.currentAIModelInUseText = "Current Loaded Model: "
        self.currentAIModelInUse.setGeometry(0, 80, self.width(), 20)
        self.currentAIModelInUse.setText(self.currentAIModelInUseText +
                                         "model.txt")
        self.currentAIModelInUse.show()
        '''
            This code just adds the submenus (actions) to the
            file menu.
        '''
        self.optionsMenu.addAction(self.togglePause)
        self.optionsMenu.addAction(self.toggleTraining)
        self.optionsMenu.addAction(self.loadModel)

        self.width = width  # Width of the window in pixels
        self.height = height  # Height pf the window in pixels
        self.title = title  # The title of the window
        self.setGeometry(x, y, self.width, self.height)
        self.setWindowTitle(
            self.title)  # Sets the title to the string specified
        '''
            It's hard to see the entire QTable if we don't put it
            inside of a QScrollArea. It will allow you to see
            the entirety of the QTable this way.
        '''
        self.qTableLabel = QLabel(self)
        self.qTableScroller = QScrollArea(self)
        self.qTableScroller.setGeometry(0, 100, self.width, self.height // 2)

        self.screenRecorderObj = mss(
        )  # A handle to the screen recording object
        self.recordingViewport = None  # The viewport that the screen will record from
        self.recordingRate = 60  # The number of times per second that we will grab a new frame from the screen

        self.currentCapture = None  # The current frame that was just captured
        self.videoFeed = QLabel(
            self)  # The video feed object drawn to the window
        self.globalTimer = QTimer(
            self)  # A global timer to keep track of when to grab a screenshot

        self.isPaused = True  # Keeps track of if the AI is paused or not currently
        self.isTraining = True  # Keeps track of if we are in debug mode or not
        self.currentAgent = None  # Keeps track of the current agent parameters
        self.currentModelFile = None  # Keeps track of the current model we have loaded

    '''
        :desc:
            Creates the window when the function is called.
            It starts the global timer for updating the window
            and it also shows the video feed and renders it
            to the screen.
    '''

    def create(self):
        self.globalTimer.start(1000 // self.recordingRate)
        self.videoFeed.show()
        self.show()

    '''
        :desc:
            This takes in an image and sets our
            video feed equal to the image that's passed in.
            
        :param frame:
            This is the current frame of the screen
            capture that the user grabs
            
        :param currentAction:
            This is the current action that the agent just
            took. It gets passed to this function in order to render it in the status bar.
            
        :param agent:
            This is the agent with the most updated parameters. Once again,
            it really just gets passed here so that we can take the QTable data
            from it in order to display it.
    '''

    def setCaptureFrame(self,
                        currentEpisode=None,
                        currentAction=None,
                        agent=None):
        stateText = self.aiStateText  # Stores a temporary state text variable
        self.currentModelFile = agent.model_file  # Sets the current model file to whatever the agent is using
        '''
            If the program is paused, then update the
            state text to reflect it.
        '''
        if self.isPaused:
            stateText += "PAUSED\t"
        else:  # If we aren't paused, then reflect it in the state text
            stateText += "UNPAUSED\t"
        '''
            If the current program is not in training mode,
            then we want to show the current AI debug video feed.
            This is just so that we can see exactly what our
            image processing has done to the source frame so that
            we can make sure that it did it correctly.
            
            This was mostly used when we were working with template matching,
            but it's still a good feature to have around so it stayed.
        '''
        if not self.isTraining:
            stateText += "DEBUG\t"  # We're currently in debug mode, so reflect it in the state text
            '''
                Below we are just setting the current video feed and
                converting the parameters to a better format so that
                it can fit on the entire screen
            '''
            if agent is not None:
                if agent.processedImage is not None:
                    frame = agent.processedImage
                    frame = cv2.resize(
                        frame,
                        (int(frame.shape[1] * 3), int(frame.shape[0] * 3)))
                    self.currentCapture = QPixmap.fromImage(
                        QImage(frame.tobytes(), frame.shape[1], frame.shape[0],
                               QImage.Format_Grayscale8))
                    self.videoFeed.resize(frame.shape[1], frame.shape[0])
                    self.videoFeed.move(self.width / 2 - frame.shape[1] / 2,
                                        self.height / 2 - frame.shape[0] / 2)
                    self.videoFeed.setPixmap(
                        self.currentCapture
                    )  # Lastly, we show the video feed by setting the pixmap
        else:  # If we're in training mode
            if agent is not None:  # As long as the agent has been initialized we can train
                '''
                    Update the stored version of the agent so that we can make
                    sure that we have the most up to date Q-Table and other variables
                '''
                self.currentAgent = agent

                stateText += "TRAINING"  # Reflect that we're training in the state text

                qTable = agent.q_table  # Gets a copy of the Q-Table from the agent
                '''
                    Here we add a header to the QScrollArea that labels it as the
                    Q-Table (in case it wasn't clear)
                '''
                outputText = ("-" * 68) + "QTable" + ("-" * 68) + "\n\n"
                '''
                    The Q-Table is stored as a dictionary, so we loop through
                    all the keys and value pairs so that we can write them in the
                    QScrollArea.
                '''
                for key, value in qTable.items():
                    outputText += "\tKey: {}\tValue: {}\n".format(
                        str(key), str(value))
                '''
                    Here we store the text we created from the Q-Table and
                    change the size of the label that we use to write it to
                    the ScrollArea with.
                '''
                self.qTableLabel.setText(outputText)

                self.qTableLabel.setGeometry(0, 0, self.qTableScroller.width(),
                                             self.height //
                                             2)  # Sets the label size
                self.qTableScroller.setWidget(
                    self.qTableLabel)  # Adds the label to the scroll area
                self.qTableScroller.hide()  # Hides the old scroller
                self.qTableScroller.show()  # Updates it by re-showing it
        '''
            If the current episode is set equal to some value, then we need
            to update the status bar (at the very bottom of the screen) to
            reflect the current episode that we're on, as well as the last
            action that was taken.
        '''
        if currentEpisode is not None:
            self.statusBar().showMessage("Current Episode: " +
                                         str(currentEpisode) +
                                         "\tCurrent Action: " + currentAction)
        self.aiStateLabel.setText(
            stateText)  # Sets the state text we gathered from this method
        self.update()  # Updates the entire main window widget

    '''
        :desc:
            This sets the rate (in frames per second)
            that the window will regrab a screenshot. In other
            words, you can set this to the FPS of the
            emulator to get a 1-1 frame-rate capture.
        
        :param timeInFPS:
            This is the fps that you want to record at.
    '''

    def setRecordRate(self, timeInFPS):
        self.recordingRate = timeInFPS

    '''
        :desc:
            This is the function that the user
            wants to be called every single time the
            window updates.
            
        :param func:
            This is the function that will be called
            every frame the window updates.
    '''

    def setUpdateFunc(self, func):
        self.globalTimer.timeout.connect(func)

    '''
        :desc:
            This sets the viewport (rectangle) of the screen
            that will be grabbed for recording.
        
        :param left:
            The number of pixels from the left of your
            screen the screen recording rectangle will start
            from.
            
        :param top:
            The number of pixels from the top of your
            screen the screen recording rectangle will start
            from.
            
        :param width:
            The width in pixels of the viewport rectangle
            
        :param height:
            The height in pixels of the viewport rectangle
    '''

    def setRecordingViewport(self, left, top, width, height):
        self.recordingViewport = {
            "left": left,
            "top": top,
            "width": width,
            "height": height
        }

    '''
        :desc:
            This actually grabs the screenshot from the window
            using the screen recording object we created earlier.
        
        :returns:
            Returns the current image that was in the screenshot
    '''

    def grabScreenshot(self):
        sourceImg = self.screenRecorderObj.grab(
            self.recordingViewport)  # Grabs the source from the desktop
        img = Image.frombytes("RGB", sourceImg.size, sourceImg.rgb, "raw",
                              "BGR")  # Converts it to a better format
        return img

    '''
        :desc:
            This function will toggle the current
            paused state when it gets called.
    '''

    def pauseFunc(self):
        self.isPaused = not self.isPaused

    '''
        :desc:
            This function will toggle between training mode
            and debug mode. It will hide the appropriate widgets that
            don't get used for this mode, and it will show the ones
            that need to be seen.
    '''

    def toggleTrainingFunc(self):
        self.isTraining = not self.isTraining  # Toggles the training state
        '''
            If we are in training mode after the swap
        '''
        if self.isTraining:
            self.videoFeed.hide()  # Hide the video feed
            self.qTableScroller.show()  # Show the scroller
            self.qTableLabel.show()  # SHow the label
        else:  # If we're in debug mode
            self.videoFeed.show()  # Show the video feed
            self.qTableScroller.hide()  # Hides the scroller
            self.qTableLabel.hide()  # Hides the label

    '''
        :desc:
            This is the Save-As function. It gets the user input
            and saves the Q-Table as whatever the user wants to save
            it as.
    '''

    def saveAsFunc(self):
        '''
            Gets the user input in a file dialog
        '''
        fileName, _ = QFileDialog.getSaveFileName(self, "Save Model")
        '''
            As long as the user actually entered a file name
            (and didn't hit cancel), then grab the file name
            they entered and use it.
        '''
        if fileName is not None and len(fileName) > 0:
            print("Trying to save: {}".format(fileName))
            self.currentAgent.save_model(fileName)

    '''
        :desc:
            This function saves the current file to whatever
            the open file is.
    '''

    def saveFunc(self):
        '''
            If the user hasn't entered a custom file name,
            then use the default.
        '''
        if self.currentModelFile is not None:
            self.currentAgent.save_model(
            )  # Saves the model with the default name
        else:
            '''
                 If the user has entered another file name,
                 either by loading a new file or clicking save-as,
                 then use it. 
             '''
            self.currentAgent.save_model(
                self.currentModelFile)  # Saves the file with the custom name

    '''
        :desc:
            This function will get the user input for a file to load to be
            used as the model. It will then reflect the changes in the Q-Table scroller
    '''

    def loadModelFunc(self):
        fileName, _ = QFileDialog.getOpenFileName(self, "Load Model")
        if fileName is not None and len(fileName) > 0:
            print("Trying to load: {}".format(fileName))
            self.currentModelFile = fileName
            self.currentAgent.load_model(fileName)
            self.currentAIModelInUse.setText(self.currentAIModelInUseText +
                                             fileName[fileName.rfind("/") +
                                                      1:])

    '''
        :desc:
            This function will open up a popup
            box whenever the user needs a reference to the
            shortcuts.
    '''

    def helpFunc(self):
        msgBox = QMessageBox()
        msgBox.setInformativeText(
            "Shortcuts Help: ctrl + h\nSave: ctrl + s\nSave-As: ctrl + alt + s\n"
            "Load Model: ctrl + k\nPause: ctrl + p\nToggle training/debug: ctrl + t"
        )

        msgBox.setWindowTitle("Shortcuts Reference Menu")
        msgBox.setStandardButtons(QMessageBox.Ok)
        msgBox.resize(500, 300)
        returnValue = msgBox.exec()
        msgBox.show()
Ejemplo n.º 59
0
    def _init_ui(self, communication_channels, config):
        grid_layout = QGridLayout()
        grid_layout.setVerticalSpacing(5)

        commonOptionsFormWidget = CommonOptionsFormWidget(
            communication_channels, config)
        monitoredAreaFormWidget = MonitoredAreaFormWidget(
            communication_channels)
        trackerWidget = TrackerWidget(communication_channels, config)
        monitoredAreaFormWidget.setDisabled(True)
        trackerWidget._update_config_options(config)
        grid_layout.addWidget(commonOptionsFormWidget, 0, 0)
        grid_layout.addWidget(monitoredAreaFormWidget, 1, 0)
        grid_layout.addWidget(trackerWidget, 2, 0)

        # setup the scroll area
        scroll_area = QScrollArea()
        scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        scroll_area.setWidgetResizable(True)
        scroll_area.setEnabled(True)

        scroll_area_widget = QWidget()
        scroll_area_widget.setMinimumWidth(800)
        scroll_area_widget.setLayout(grid_layout)
        scroll_area.setWidget(scroll_area_widget)

        form_layout = QVBoxLayout()
        form_layout.addWidget(scroll_area)

        self.setLayout(form_layout)
Ejemplo n.º 60
0
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)

        # Структура главного окна
        # Создаем меню
        self.menu_bar = self.menuBar()

        # Создаем блоки меню
        # Блок меню 'Учет движения товаров'

        self.gma_menu = self.menu_bar.addMenu('Учет движения товаров')
        self.gma_menu.setEnabled(False)
        self.ro_open_btn = QAction(self)
        self.ro_open_btn.setText('Приходный ордер')
        self.wo_open_btn = QAction(self)
        self.wo_open_btn.setText('Расходный ордер')
        self.gma_menu.addAction(self.ro_open_btn)
        self.gma_menu.addAction(self.wo_open_btn)

        # Блок меню 'Отчеты'

        self.r_menu = self.menu_bar.addMenu('Отчеты')
        self.r_menu.setEnabled(False)
        self.tws_report_btn = QAction(self)
        self.tws_report_btn.setText('Операции с поставщиками')
        self.gis_report_btn = QAction(self)
        self.gis_report_btn.setText('Товары в наличии')
        self.r_menu.addAction(self.tws_report_btn)
        self.r_menu.addAction(self.gis_report_btn)

        # Блок меню 'Справочники'
        self.d_menu = self.menu_bar.addMenu('Справочники')
        self.d_menu.setEnabled(False)

        self.u_catalog_btn = QAction(self)
        self.u_catalog_btn.setText('Пользователи')

        self.r_catalog_btn = QAction(self)
        self.r_catalog_btn.setText('Права пользователей')

        self.c_catalog_btn = QAction(self)
        self.c_catalog_btn.setText('Категории')

        self.n_catalog_btn = QAction(self)
        self.n_catalog_btn.setText('Номенклатура товаров')

        self.un_catalog_btn = QAction(self)
        self.un_catalog_btn.setText('Единицы измерения')

        self.s_catalog_btn = QAction(self)
        self.s_catalog_btn.setText('Поставщики')

        self.p_catalog_btn = QAction(self)
        self.p_catalog_btn.setText('Должности')

        self.e_catalog_btn = QAction(self)
        self.e_catalog_btn.setText('Сотрудники')

        self.d_menu.addAction(self.u_catalog_btn)
        self.d_menu.addAction(self.r_catalog_btn)
        self.d_menu.addAction(self.c_catalog_btn)
        self.d_menu.addAction(self.n_catalog_btn)
        self.d_menu.addAction(self.un_catalog_btn)
        self.d_menu.addAction(self.s_catalog_btn)
        self.d_menu.addAction(self.p_catalog_btn)
        self.d_menu.addAction(self.e_catalog_btn)

        # Верхний виджет с полным путем до файла БД

        self.db_lbl = QLabel()
        self.db_lbl.setText('Путь до БД:')
        self.db_lbl.setStyleSheet("border-style: none;" "font-size: 10pt;")
        self.db_path_lbl = QLineEdit()
        self.db_path_lbl.setStyleSheet(
            "background-color: white;"
            "font-size: 10pt;"
            "color: green;")
        self.db_path_lbl.setFixedSize(700, 25)
        self.db_path_lbl.setEnabled(False)
        self.db_path_btn = QPushButton('...')
        self.db_path_btn.setFixedSize(25, 25)
        self.db_path_btn.setStyleSheet(
            "border-width: 1px;"
            "border-style: solid;"
            "border-color: dimgray;"
            "border-radius: 5px;"
            "background-color: gainsboro;")
        self.db_path_btn.clicked.connect(self.on_db_path_btn_clicked)

        self.tdw = QDockWidget()
        self.tdw.setFixedHeight(65)
        self.tdw.setFeatures(self.tdw.NoDockWidgetFeatures)
        self.tdw_grid = QGridLayout()
        self.tdw_grid.setColumnStretch(3, 1)
        self.tdw_grid.addWidget(self.db_lbl)
        self.tdw_grid.addWidget(self.db_path_lbl)
        self.tdw_grid.addWidget(self.db_path_btn)
        self.tdw_frame = QFrame()
        self.tdw_frame.setStyleSheet(
            "background-color: ghostwhite;"
            "border-width: 0.5px;"
            "border-style: solid;"
            "border-color: silver;")
        self.tdw_frame.setLayout(self.tdw_grid)
        self.tdw.setWidget(self.tdw_frame)
        self.addDockWidget(QtCore.Qt.TopDockWidgetArea, self.tdw)

        # Левый виджет с окном каталога продукции

        self.ldw = QDockWidget()
        self.ldw.setFixedSize(500, 570)
        self.ldw.setFeatures(self.ldw.NoDockWidgetFeatures)
        self.ldw_tree = QTreeView()
        self.ldw_tree.setFixedSize(500, 530)
        self.ldw_tree.setHeaderHidden(True)
        self.ldw_tree_model = QStandardItemModel()
        self.ldw_tree.setModel(self.ldw_tree_model)
        self.ldw_tree.clicked.connect(self.on_ldw_tree_clicked)
        self.outf_scroll = QScrollArea()
        self.outf_scroll.setWidget(self.ldw_tree)
        self.ldw.setWidget(self.outf_scroll)
        self.ldw.setWindowTitle("Каталог продукции")

        # Центральный виджет с карточкой товара

        self.cdw = QDockWidget()
        self.cdw.setFeatures(self.cdw.NoDockWidgetFeatures)
        #self.setCentralWidget(self.cdw)

        # Нижний виджет со служебными сообщениями

        self.smdw = QDockWidget()
        self.smdw.setFixedHeight(140)
        self.smdw.setFeatures(self.smdw.NoDockWidgetFeatures)
        self.sm_list_widget = QListWidget()
        self.smdw.setWidget(self.sm_list_widget)
        self.smdw.setWindowTitle("Служебные сообщения")