Exemplo n.º 1
1
 def __init__(self):
     super().__init__()
     self.time_label = QLabel('', self)
     self.speed_label = QLabel('', self)
     self.characters_label = QLabel('', self)
     self.expl_tabel = QLabel('', self)
     self.initUI()
Exemplo n.º 2
1
 def _get_label(item):
     """
     Add label for organization.
     """
     l = QLabel(item.name)
     l.setObjectName(str(item.id))
     return l
Exemplo n.º 3
1
    def __init__(self, url, color):
        QWidget.__init__(self)
        self.setStyleSheet("background-color: black")

        self.file_name_font = QFont()
        self.file_name_font.setPointSize(24)

        self.file_name_label = QLabel(self)
        self.file_name_label.setText(url)
        self.file_name_label.setFont(self.file_name_font)
        self.file_name_label.setAlignment(Qt.AlignCenter)
        self.file_name_label.setStyleSheet("color: #eee")

        self.qrcode_label = QLabel(self)

        self.notify_font = QFont()
        self.notify_font.setPointSize(12)
        self.notify_label = QLabel(self)
        self.notify_label.setText("Scan above QR to copy information")
        self.notify_label.setFont(self.notify_font)
        self.notify_label.setAlignment(Qt.AlignCenter)
        self.notify_label.setStyleSheet("color: #eee")

        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addStretch()
        layout.addWidget(self.qrcode_label, 0, Qt.AlignCenter)
        layout.addSpacing(20)
        layout.addWidget(self.file_name_label, 0, Qt.AlignCenter)
        layout.addSpacing(40)
        layout.addWidget(self.notify_label, 0, Qt.AlignCenter)
        layout.addStretch()

        self.qrcode_label.setPixmap(qrcode.make(url, image_factory=Image).pixmap())
Exemplo n.º 4
1
 def animationLabel(self, index, animationFile, speed=100):
     """
     Public slot to set an animated icon.
     
     @param index tab index (integer)
     @param animationFile name of the file containing the animation (string)
     @param speed animation speed of the icon in percent of the original
         icon's speed (integer)
     @return reference to the created label (QLabel)
     """
     if index == -1:
         return None
     
     if hasattr(self.__tabBar, 'setTabButton'):
         side = self.__freeSide()
         animation = QLabel(self)
         if animationFile and not animation.movie():
             movie = QMovie(animationFile, QByteArray(), animation)
             movie.setSpeed(speed)
             animation.setMovie(movie)
             movie.start()
         self.__tabBar.setTabButton(index, side, None)
         self.__tabBar.setTabButton(index, side, animation)
         return animation
     else:
         return None
Exemplo n.º 5
1
class MyWindow(QMainWindow):

    def __init__(self):
        super().__init__()

        # 가로 슬라에더 생성
        self.slider = QSlider(Qt.Horizontal, self)  #<---- 1
        self.slider.setMaximum(1000)                #<---- 2
        self.slider.setMinimum(0)                   #<---- 3

        # 위치와 크기
        self.slider.setGeometry(30, 40, 100, 30)

        # 시그널 연결
        self.slider.valueChanged[int].connect(self.changeValue)  #<---- 4

        # 라벨 생성
        self.label = QLabel("current : 0", self)    #<----- 5
        self.label.setGeometry(30,70, 100, 30)

        # 윈도우 위치
        self.setGeometry(300, 300, 280, 170)
        self.setWindowTitle('Slider Example')
        self.show()


    def changeValue(self, value):                  #<----- 6
        "슬라이더 값 출력"
        self.label.setText("current : {}".format(value))  #<----- 7
Exemplo n.º 6
0
    def __init__(self, parent=None):
        super().__init__(parent)

        self.create_title_layout = QHBoxLayout()
        self.collection_title_layout = QHBoxLayout()
        self.local_title_layout = QHBoxLayout()

        self.recommend_title = QLabel(u'推荐')
        self.create_title = QLabel(u'创建的歌单')
        self.collection_title = QLabel(u'收藏的歌单')
        self.local_title = QLabel(u'本地歌单')

        self.create_fold_spread_btn = QPushButton()
        self.collection_fold_spread_btn = QPushButton()
        self.local_fold_spread_btn = QPushButton()

        self.new_playlist_btn = QPushButton('+')

        self.recommend_list_widget = SpreadWidget()
        self.create_list_widget = SpreadWidget()
        self.collection_list_widget = SpreadWidget()
        self.local_list_widget = SpreadWidget()

        self.fm_item = RecommendItem(self.recommend_list_widget, "私人FM",
                                     QPixmap(ICON_PATH + '/fm.png'))
        self.recommend_item = RecommendItem(
            self.recommend_list_widget,
            "每日推荐",
            QPixmap(ICON_PATH + '/recommend.png'))

        self.layout = QVBoxLayout()

        self.set_widgets_prop()
        self.set_layouts_prop()
        self.set_me()
Exemplo n.º 7
0
    def __init__(self, parent=None):
        super(ModeShiftDialog, self).__init__(parent)
        
        mainLayout = QGridLayout()
        self.setLayout(mainLayout)
        
        self.keyLabel = QLabel()
        self.keyInput = QLineEdit()
        self.modeCombo = QComboBox()
        self.modeLabel = QLabel()
        
        self.buttons = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        userguide.addButton(self.buttons, "mode_shift")
        
        for m in sorted(modes.keys()):
            self.modeCombo.addItem(m)

        mainLayout.addWidget(self.keyLabel, 0, 0, 1, 1)
        mainLayout.addWidget(self.keyInput, 0, 1, 1, 1)
        mainLayout.addWidget(self.modeLabel, 1, 0, 1, 1)
        mainLayout.addWidget(self.modeCombo, 1, 1, 1, 1)
        mainLayout.addWidget(self.buttons, 9, 0, 2, 2)
        
        app.translateUI(self)
        qutil.saveDialogSize(self, "mode_shift/dialog/size", QSize(80, 60))
        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)
        
        self.keyInput.textEdited.connect(self.readKeyInput)
        self.modeCombo.currentIndexChanged.connect(self.readSettings)
        
        self.loadSettings()
Exemplo n.º 8
0
class ImgurAuthenticationDialog(QDialog):
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)

        self.setWindowModality(Qt.ApplicationModal)

        layout = QVBoxLayout(self)

        self.url = QLabel(self)
        self.input = QLineEdit(self)
        layout.addWidget(self.url)
        layout.addWidget(self.input)

        self.url.setWordWrap(True)
        self.url.setOpenExternalLinks(True)

        self.input.editingFinished.connect(self.accept)

    @staticmethod
    def getImgurPin(parent=None, window_title="", label_text=""):
        dialog = ImgurAuthenticationDialog(parent)
        dialog.setWindowTitle(window_title)
        dialog.url.setText(label_text)
        result = dialog.exec_()
        return result, dialog.input.text()
Exemplo n.º 9
0
    def __init__(self, parent, cli_iface, iface_name):
        super(ControlPanelWindow, self).__init__(parent)
        self.setWindowTitle('SLCAN Adapter Control Panel')
        self.setAttribute(Qt.WA_DeleteOnClose)              # This is required to stop background timers!

        self._cli_iface = cli_iface
        self._iface_name = iface_name

        self._state_widget = StateWidget(self, self._cli_iface)
        self._config_widget = ConfigWidget(self, self._cli_iface)
        self._cli_widget = CLIWidget(self, self._cli_iface)

        self._tab_widget = QTabWidget(self)
        self._tab_widget.addTab(self._state_widget, get_icon('dashboard'), 'Adapter State')
        self._tab_widget.addTab(self._config_widget, get_icon('wrench'), 'Configuration')
        self._tab_widget.addTab(self._cli_widget, get_icon('terminal'), 'Command Line')

        self._status_bar = QStatusBar(self)
        self._status_bar.setSizeGripEnabled(False)

        iface_name_label = QLabel(iface_name.split('/')[-1], self)
        iface_name_label.setFont(get_monospace_font())

        layout = QVBoxLayout(self)
        layout.addWidget(iface_name_label)
        layout.addWidget(self._tab_widget)
        layout.addWidget(self._status_bar)

        left, top, right, bottom = layout.getContentsMargins()
        bottom = 0
        layout.setContentsMargins(left, top, right, bottom)

        self.setLayout(layout)
        self.resize(400, 400)
Exemplo n.º 10
0
    def __init__(self,event):
        super().__init__()
        print(event)
        self.vbox = QVBoxLayout()

        self.eventData = QLabel()
        self.eventData.setText('Id: {} Required access: {}'.format(
            str(event['id']),event['required_access']
        ))
        self.eventName = QLabel()
        self.eventName.setText(event['name'])
        self.eventDescription = QLabel()
        self.eventDescription.setText(event['description'])
        self.eventRequirement = QLabel()
        self.eventRequirement.setText(event['requirement'])
        self.eventRewards = QLabel()
        self.eventRewards.setText('Rewards:')
        self.vbox.addWidget(self.eventData)
        self.vbox.addWidget(self.eventName)
        self.vbox.addWidget(self.eventDescription)
        self.vbox.addWidget(self.eventRequirement)
        self.vbox.addWidget(self.eventRewards)
        self.resize(self.vbox.sizeHint())
        self.setLayout(self.vbox)

        self.threads = []
        for i in event['rewards']:
            self.threads.append(loadThread(r'https://api.guildwars2.com/v2/items/' + str(i['id'])))
            self.threads[-1].metaEventSignal.connect(self.addReward, Qt.QueuedConnection)
            self.threads[-1].start()
Exemplo n.º 11
0
 def __showTabPreview(self):
     """
     Private slot to show the tab preview.
     """
     indexedBrowser = self.__tabWidget.browserAt(
         self.__currentTabPreviewIndex)
     currentBrowser = self.__tabWidget.currentBrowser()
     
     if indexedBrowser is None or currentBrowser is None:
         return
     
     # no previews during load
     if indexedBrowser.progress() != 0:
         return
     
     w = self.tabSizeHint(self.__currentTabPreviewIndex).width()
     h = int(w * currentBrowser.height() / currentBrowser.width())
     
     self.__previewPopup = E5PassivePopup(self)
     self.__previewPopup.setFrameShape(QFrame.StyledPanel)
     self.__previewPopup.setFrameShadow(QFrame.Plain)
     self.__previewPopup.setFixedSize(w, h)
     
     from .HelpSnap import renderTabPreview
     label = QLabel()
     label.setPixmap(renderTabPreview(indexedBrowser.page(), w, h))
     
     self.__previewPopup.setView(label)
     self.__previewPopup.layout().setAlignment(Qt.AlignTop)
     self.__previewPopup.layout().setContentsMargins(0, 0, 0, 0)
     
     tr = self.tabRect(self.__currentTabPreviewIndex)
     pos = QPoint(tr.x(), tr.y() + tr.height())
     
     self.__previewPopup.show(self.mapToGlobal(pos))
Exemplo n.º 12
0
    def initUi (self, delete_entries):
        delete_entries.setObjectName(_fromUtf8("delete_entries"))
        delete_entries.resize(472, 239)
        self.button_exit = QPushButton(delete_entries)
        self.button_exit.setGeometry(QtCore.QRect(350, 200, 110, 32))
        self.button_exit.setObjectName(_fromUtf8("button_exit"))
        self.button_delete = QPushButton(delete_entries)
        self.button_delete.setGeometry(QtCore.QRect(240, 200, 110, 32))
        self.button_delete.setObjectName(_fromUtf8("button_delete"))
        self.edit = QTextEdit(delete_entries)
        self.edit.setGeometry(QtCore.QRect(20, 50, 431, 141))
        self.edit.setObjectName(_fromUtf8("edit"))
        self.label = QLabel(delete_entries)
        self.label.setGeometry(QtCore.QRect(60, 0, 431, 31))
        self.label.setObjectName(_fromUtf8("label"))
        self.label_2 = QLabel(delete_entries)
        self.label_2.setGeometry(QtCore.QRect(50, 20, 431, 31))
        self.label_2.setObjectName(_fromUtf8("label_2"))

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

        #self.connect(self.button_exit, QtCore.SIGNAL("released()"), self.exit)
        #self.connect(self.button_delete, QtCore.SIGNAL("released()"), self.suppression)
        self.button_exit.clicked.connect(self.exit)
        self.button_delete.clicked.connect(self.suppression)
Exemplo n.º 13
0
 def __showInfo(self):
     """
     Private slot to show information about the blocked object.
     """
     dlg = QDialog()
     dlg.setWindowTitle(self.tr("Flash Object"))
     dlg.setSizeGripEnabled(True)
     layout = QFormLayout(dlg)
     layout.addRow(QLabel(self.tr("<b>Attribute Name</b>")),
                   QLabel(self.tr("<b>Value</b>")))
     
     index = 0
     for name in self.__argumentNames:
         nameLabel = QLabel(self.__elide(name, length=30))
         value = self.__argumentValues[index]
         valueLabel = QLabel(self.__elide(value, length=60))
         valueLabel.setTextInteractionFlags(
             Qt.TextSelectableByMouse | Qt.LinksAccessibleByMouse)
         layout.addRow(nameLabel, valueLabel)
         
         index += 1
     
     if index == 0:
         layout.addRow(QLabel(self.tr("No information available.")))
     
     dlg.setMaximumHeight(500)
     dlg.setMaximumWidth(500)
     dlg.exec_()
Exemplo n.º 14
0
 def __init__(self, parent, name):
     QWidget.__init__(self, parent)
     self.setStyleSheet(get_stylesheet("ribbonPane"))
     horizontal_layout = QHBoxLayout()
     horizontal_layout.setSpacing(0)
     horizontal_layout.setContentsMargins(0, 0, 0, 0)
     self.setLayout(horizontal_layout)
     vertical_widget = QWidget(self)
     horizontal_layout.addWidget(vertical_widget)
     horizontal_layout.addWidget(RibbonSeparator(self))
     vertical_layout = QVBoxLayout()
     vertical_layout.setSpacing(0)
     vertical_layout.setContentsMargins(0, 0, 0, 0)
     vertical_widget.setLayout(vertical_layout)
     label = QLabel(name)
     label.setAlignment(Qt.AlignCenter)
     label.setStyleSheet("color:#666;")
     content_widget = QWidget(self)
     vertical_layout.addWidget(content_widget)
     vertical_layout.addWidget(label)
     content_layout = QHBoxLayout()
     content_layout.setAlignment(Qt.AlignLeft)
     content_layout.setSpacing(0)
     content_layout.setContentsMargins(0, 0, 0, 0)
     self.contentLayout = content_layout
     content_widget.setLayout(content_layout)
class HelpForm(QDialog):
    def __init__(self,  page,  parent=None):
        super(HelpForm, self).__init__(parent)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setWindowModality(Qt.WindowModal)
        # actions
        backAction = QAction(QIcon(":/back.png"), "&Back", self)
        backAction.setShortcut(QKeySequence.Back)
        homeAction = QAction(QIcon(":/home.png"), "&Home", self)
        homeAction.setShortcut("Home")
        self.pageLabel = QLabel()
        #toolbar
        toolBar = QToolBar()
        toolBar.addAction(backAction)
        toolBar.addAction(homeAction)
        toolBar.addWidget(self.pageLabel)
        self.textBrowser = QTextBrowser()
        # layout
        layout = QVBoxLayout()
        layout.addWidget(toolBar)
        layout.addWidget(self.textBrowser, 1)
        self.setLayout(layout)
        # signals and slots
        backAction.triggered.connect(self.textBrowser.backward)
        homeAction.triggered.connect(self.textBrowser.home)
        self.textBrowser.sourceChanged.connect(self.updatePageTitle)
        self.textBrowser.setSearchPaths([":/help"])
        self.textBrowser.setSource(QUrl(page))
        self.resize(400, 600)
        self.setWindowTitle("{0} Help".format(
            QApplication.applicationName()))
    def updatePageTitle(self):
        self.pageLabel.setText(self.textBrowser.documentTitle())
Exemplo n.º 16
0
    def __init__(self, win):
        QWidget.__init__(self)
        self.win = win
        self.setWindowTitle('Electrum - '+_('Payment Request'))
        self.setMinimumSize(800, 250)
        self.address = ''
        self.label = ''
        self.amount = 0
        self.setFocusPolicy(QtCore.Qt.NoFocus)

        main_box = QHBoxLayout()

        self.qrw = QRCodeWidget()
        main_box.addWidget(self.qrw, 1)

        vbox = QVBoxLayout()
        main_box.addLayout(vbox)

        self.address_label = QLabel("")
        #self.address_label.setFont(QFont(MONOSPACE_FONT))
        vbox.addWidget(self.address_label)

        self.label_label = QLabel("")
        vbox.addWidget(self.label_label)

        self.amount_label = QLabel("")
        vbox.addWidget(self.amount_label)

        vbox.addStretch(1)
        self.setLayout(main_box)
Exemplo n.º 17
0
class Example(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):

        vbox = QVBoxLayout()

        btn = QPushButton('dialog', self)
        btn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

        btn.move(20, 20)

        vbox.addWidget(btn)

        btn.clicked.connect(self.showDialog)

        self.lbl = QLabel('knowledge only matters', self)
        self.lbl.move(130, 20)

        vbox.addWidget(self.lbl)
        self.setLayout(vbox)

        self.setGeometry(300, 300, 300, 250)
        self.setWindowTitle('font dialog')
        self.show()

    def showDialog(self):
        font, ok = QFontDialog.getFont()
        if ok:
            self.lbl.setFont(font)
Exemplo n.º 18
0
    def display_model(self):
        """
        Clear widget and display items.
        """

        utils.clear_layout(self.layout)

        self.columns = []
        j = 0

        columns = [c.name for c in self.model.__table__.columns] + ['report']
        for c in columns:
            if c not in self._columns_to_display:
                continue
            self.columns.append(c)
            l = QLabel(_(c))
            l.setObjectName('header')
            l.setAlignment(Qt.AlignCenter)
            self.header_layout.addWidget(l, 0, j)
            j += 1

        for i, item in enumerate(self.items[self.current_items_index:self.current_items_index + self.ITEMS_PER_PAGE], 0):
            self._add_row(i, item)

        empty = QWidget()
        empty.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)
        self.layout.addWidget(empty, self.layout.rowCount(), 0)
Exemplo n.º 19
0
class GeneralTab(QTabWidget):
    def __init__(self, parent, result):
        QTabWidget.__init__(self, parent)
        self.result = result
        self.parent = parent

        obs_box = QGroupBox("Observation Window:", self)

        obs = QHBoxLayout()
        self.obs_label = QLabel()
        obs.addWidget(self.obs_label)
        obs_conf = QPushButton("Configure...")
        obs_conf.clicked.connect(self.setObservationWindow)
        obs.addWidget(obs_conf)

        obs_box.setLayout(obs)

        self.setLayout(QVBoxLayout())
        self.layout().addWidget(obs_box)
        self.load_table = LoadTable(self, result)
        self.layout().addWidget(self.load_table)
        self.update()

    def setObservationWindow(self):
        dialog = ObservationWindowConfigure(self.result)
        if dialog.exec_():
            self.result.observation_window = dialog.getObservationWindow()
            self.parent.update()

    def update(self):
        cycles_per_ms = self.result.model.cycles_per_ms
        self.obs_label.setText('from {:.2f} to {:.2f} ms'.format(
            self.result.observation_window[0] / float(cycles_per_ms),
            self.result.observation_window[1] / float(cycles_per_ms)))
        self.load_table.update()
Exemplo n.º 20
0
 def __init__(self, title, text, image, contributors, parent=None):
     super(AboutDialog, self).__init__(parent)
     layout = QVBoxLayout()
     titleLayout = QHBoxLayout()
     name_versionLabel = QLabel(title)
     contentsLayout = QHBoxLayout()
     aboutBrowser = QTextBrowser()
     aboutBrowser.append(text)
     aboutBrowser.setOpenExternalLinks(True)
     creditsBrowser = QTextBrowser()
     creditsBrowser.append(contributors)
     creditsBrowser.setOpenExternalLinks(True)
     TabWidget = QTabWidget()
     TabWidget.addTab(aboutBrowser, self.tr('About'))
     TabWidget.addTab(creditsBrowser, self.tr('Contributors'))
     aboutBrowser.moveCursor(QTextCursor.Start)
     creditsBrowser.moveCursor(QTextCursor.Start)
     imageLabel = QLabel()
     imageLabel.setPixmap(QPixmap(image))
     titleLayout.addWidget(imageLabel)
     titleLayout.addWidget(name_versionLabel)
     titleLayout.addStretch()
     contentsLayout.addWidget(TabWidget)
     buttonLayout = QHBoxLayout()
     buttonBox = QDialogButtonBox(QDialogButtonBox.Ok)
     buttonLayout.addWidget(buttonBox)
     layout.addLayout(titleLayout)
     layout.addLayout(contentsLayout)
     layout.addLayout(buttonLayout)
     self.setLayout(layout)
     buttonBox.clicked.connect(self.accept)
     self.setMinimumSize(QSize(380, 400))
     self.setWindowTitle(self.tr('About Onkyo QT'))
Exemplo n.º 21
0
class node_indicator(QWidget):
	def __init__(self):
		QWidget.__init__(self)
		self.hbox=QHBoxLayout()
		
		self.bar=progress_class()
		self.bar.spinner.stop()
		self.bar.spinner.hide()
		self.label=QLabel()
		
		self.slider = QSlider(Qt.Horizontal)
		self.slider.setMinimum(0)
		self.slider.setMaximum(10)

		self.slider.setTickPosition(QSlider.TicksBelow)
		self.slider.setTickInterval(1)
		#self.slider.valueChanged.connect(self.slider0_change)
		self.slider.setMinimumSize(300, 80)

		self.hbox.addWidget(self.label)
		self.hbox.addWidget(self.bar)
		self.hbox.addWidget(self.slider)

		self.setLayout(self.hbox)

	def set_cpus(self,cpus):
		self.slider.setValue(cpus)
	
	def set_text(self,text):
		self.label.setText(text)
Exemplo n.º 22
0
	def __init__(self, tup_gallery, parent = None, menu = None):
		super().__init__(parent)
		self.setMaximumWidth(16777215)
		assert isinstance(tup_gallery, tuple), "Incorrect type received, expected tuple"
		assert isinstance(tup_gallery[0], str) and isinstance(tup_gallery[1], list)
		main_layout = QVBoxLayout()
		# todo make it scroll
		scroll_area = QScrollArea()
		dummy = QWidget()
		self.gallery_layout = misc.FlowLayout(dummy)
		scroll_area.setWidgetResizable(True)
		scroll_area.setMaximumHeight(400)
		scroll_area.setMidLineWidth(620)
		scroll_area.setBackgroundRole(scroll_area.palette().Shadow)
		scroll_area.setFrameStyle(scroll_area.NoFrame)
		scroll_area.setWidget(dummy)
		text = tup_gallery[0]
		galleries = tup_gallery[1]
		main_layout.addWidget(scroll_area, 3)
		for g in galleries:
			gall_w = misc.GalleryShowcaseWidget(parent=self, menu=menu())
			gall_w.set_gallery(g, (170//1.40, 170))
			gall_w.double_clicked.connect(self.gallery_doubleclicked.emit)
			self.gallery_layout.addWidget(gall_w)

		text_lbl =  QLabel(text)
		text_lbl.setAlignment(Qt.AlignCenter)
		main_layout.addWidget(text_lbl)
		main_layout.addLayout(self.buttons_layout)
		self.main_widget.setLayout(main_layout)
		self.setMaximumHeight(500)
		self.setMaximumWidth(620)
		self.resize(620, 500)
		self.show()
Exemplo n.º 23
0
    def __init__(self, parent):
        super(LilyPondPreferences, self).__init__(parent)

        grid = QGridLayout()
        self.setLayout(grid)

        self.pitchLanguageLabel = QLabel()
        self.pitchLanguage = QComboBox()
        self.versionLabel = QLabel()
        self.version = QComboBox(editable=True)

        self.pitchLanguage.addItem('')
        self.pitchLanguage.addItems([lang.title() for lang in sorted(scoreproperties.keyNames)])
        self.version.addItem(lilypondinfo.preferred().versionString())
        for v in ("2.18.0", "2.16.0", "2.14.0", "2.12.0"):
            if v != lilypondinfo.preferred().versionString():
                self.version.addItem(v)

        grid.addWidget(self.pitchLanguageLabel, 0, 0)
        grid.addWidget(self.pitchLanguage, 0, 1)
        grid.addWidget(self.versionLabel, 1, 0)
        grid.addWidget(self.version, 1, 1)

        self.pitchLanguage.activated.connect(self.slotPitchLanguageChanged)
        app.translateUI(self)
        self.loadSettings()
        self.window().finished.connect(self.saveSettings)
Exemplo n.º 24
0
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setSubTitle(self.tr("<h2>Select Menu Style</h2>"))

        texts = [
            self.tr("<p>Application Menu is the default for KaOS because of its \
            extremely lightweight (and fast) structure.</p>"),
            self.tr("<p>Application Launcher is the standard for KDE. \
            Application shortcuts are arranged under a tab structure.</p>"),
            self.tr("<p>Application Panel is a full screen menu style. \
            Application shortcuts are arranged so that you can access them quickly and easily.</p>")
        ]

        self.menus = [[":/data/images/menu-kicker.png", texts[0]],
                 [":/data/images/menu-kickoff.png", texts[1]],
                 [":/data/images/menu-kimpanel.png", texts[2]]]

        vlayout = QVBoxLayout(self)

        labelLayout = QHBoxLayout()

        iconLabel = QLabel()
        iconLabel.setMaximumSize(64, 64)
        iconLabel.setPixmap(QIcon.fromTheme("kde").pixmap(64, 64))
        labelLayout.addWidget(iconLabel)

        label = QLabel(self)
        label.setText(self.tr("<p>You can also customize your <strong>KDE menu</strong> as you like. \
        Please choose one from the following styles.</p>"))
        labelLayout.addWidget(label)
        vlayout.addLayout(labelLayout)

        vlayout.addItem(QSpacerItem(20, 40, QSizePolicy.Preferred, QSizePolicy.Preferred))

        self.comboBox = QComboBox(self)
        self.comboBox.addItem(self.tr("Application Menu"))
        self.comboBox.addItem(self.tr("Application Launcher"))
        self.comboBox.addItem(self.tr("Application Dashboard"))
        vlayout.addWidget(self.comboBox)

        vlayout.addItem(QSpacerItem(20, 40, QSizePolicy.Preferred, QSizePolicy.Preferred))

        hlayout = QHBoxLayout(self)

        self.labelMenu = QLabel(self)
        self.labelMenu.setPixmap(QPixmap(self.menus[0][0]))
        self.labelMenu.setMaximumSize(350 ,214)
        hlayout.addWidget(self.labelMenu)
        self.labelText = QLabel(self)
        self.labelText.setWordWrap(True)
        self.labelText.setText(self.tr(self.menus[0][1]))
        hlayout.addWidget(self.labelText)

        vlayout.addLayout(hlayout)

        vlayout.addItem(QSpacerItem(20, 40, QSizePolicy.Preferred, QSizePolicy.Preferred))

        self.comboBox.currentIndexChanged.connect(self.menuSelect)

        self.menuSelected = 0
Exemplo n.º 25
0
    def _make_file_info(self, filename: str) -> QLayout:
        # Widgets
        file_icon = QLabel()
        file_icon.setPixmap(QIcon.fromTheme("document").pixmap(48))
        file_icon.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

        file_info = QLabel("Filename: <b>{}</b><br>"
                           "Size: 0 bytes<br>"
                           "Modified: Today".format(html.escape(filename)))
        file_info.setTextFormat(Qt.RichText)
        file_info.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        rename_btn = QPushButton("Rename")

        # Layout
        hbox = QHBoxLayout()
        hbox.addWidget(file_icon)
        hbox.addWidget(file_info)
        hbox.addWidget(rename_btn)

        # Signals
        if filename is self._source_filename:
            rename_btn.clicked.connect(lambda: self.done(ConflictResolution.RENAME_SOURCE.value))
        elif filename is self._target_filename:
            rename_btn.clicked.connect(lambda: self.done(ConflictResolution.RENAME_TARGET.value))

        return hbox
Exemplo n.º 26
0
    def on_emptying_tokens(self, data):
        if not data:
            return
        json_data = json.dumps(data)

        if has_qr:
            self.empty_tokens_barcode_dialog = QWidget()
            self.empty_tokens_barcode_dialog.setWindowTitle("Please scan the following QR code")
            self.empty_tokens_barcode_dialog.setGeometry(10, 10, 500, 500)
            qr = qrcode.QRCode(
                version=1,
                error_correction=qrcode.constants.ERROR_CORRECT_M,
                box_size=10,
                border=5,
            )
            qr.add_data(json_data)
            qr.make(fit=True)

            img = qr.make_image()  # PIL format

            qim = ImageQt(img)
            pixmap = QtGui.QPixmap.fromImage(qim).scaled(600, 600, QtCore.Qt.KeepAspectRatio)
            label = QLabel(self.empty_tokens_barcode_dialog)
            label.setPixmap(pixmap)
            self.empty_tokens_barcode_dialog.resize(pixmap.width(), pixmap.height())
            self.empty_tokens_barcode_dialog.show()
        else:
            ConfirmationDialog.show_error(self.window(), DEPENDENCY_ERROR_TITLE, DEPENDENCY_ERROR_MESSAGE)
Exemplo n.º 27
0
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setSubTitle(self.tr("<h2>Setup Mouse Behavior</h2>"))

        vlayout = QVBoxLayout(self)

        labelLayout = QHBoxLayout()
        imageLabel = QLabel()
        imageLabel.setPixmap(QPixmap(":/data/images/preferences-desktop-peripherals.png"))
        imageLabel.setMaximumSize(64, 64)
        labelLayout.addWidget(imageLabel)

        mouseLabel = QLabel(self)
        mouseLabel.setText(self.tr("""<p>The <strong>clicking behavior</strong> defines how many times you want
        to click when you are opening a file. If you are <strong>left handed</strong>, you may prefer to
        swap the left and right buttons of your pointing device.</p>"""))
        mouseLabel.setWordWrap(True)
        labelLayout.addWidget(mouseLabel)
        vlayout.addLayout(labelLayout)

        vlayout.addItem(QSpacerItem(20, 100, QSizePolicy.Preferred, QSizePolicy.Preferred))

        hlayout = QHBoxLayout()
        vlayout.addLayout(hlayout)

        self.createGroupBox(hlayout)

        vlayout.addItem(QSpacerItem(20, 40, QSizePolicy.Preferred, QSizePolicy.Preferred))

        self.folderSingleClick = False
        self.mouseButtonMap = "RightHanded"
        self.reverseScrollPolarity = False
Exemplo n.º 28
0
    def _show_templates(self):
        """
        Update templates on shoeEvent.
        """

        cols = 3
        templates = template_module.Template.get_all()

        for j, item in enumerate(self.visible_items):
            if not templates[item.id]:
                l = QLabel("Нет шаблонов для данного объекта\nУправлять шаблонами можно на вкладке настроек")
                l.setAlignment(Qt.AlignCenter)
                self.templates_layout.addWidget(l)
                continue
            layouts = [QVBoxLayout() for _ in range(cols)]
            for i, each in enumerate(templates[item.id]):
                b = QRadioButton(each.name)
                b.setChecked(item.template == each)
                b.clicked.connect(functools.partial(self._template_clicked, j, each))
                b.mouseDoubleClickEvent = functools.partial(self.open_template_edit_widget, j, each)
                layouts[i % cols].addWidget(b)

            wrapper = QHBoxLayout()
            for each in layouts:
                each.addStretch()
                wrapper.addLayout(each, stretch=int(100 / cols))
            self.templates_layout.addWidget(utils.get_scrollable(wrapper))
Exemplo n.º 29
0
 def _setupUi(self):
     self.setWindowTitle(tr("Error Report"))
     self.resize(553, 349)
     self.verticalLayout = QVBoxLayout(self)
     self.label = QLabel(self)
     self.label.setText(tr("Something went wrong. How about reporting the error?"))
     self.label.setWordWrap(True)
     self.verticalLayout.addWidget(self.label)
     self.errorTextEdit = QPlainTextEdit(self)
     self.errorTextEdit.setReadOnly(True)
     self.verticalLayout.addWidget(self.errorTextEdit)
     msg = tr(
         "Error reports should be reported as Github issues. You can copy the error traceback "
         "above and paste it in a new issue (bonus point if you run a search to make sure the "
         "issue doesn't already exist). What usually really helps is if you add a description "
         "of how you got the error. Thanks!"
         "\n\n"
         "Although the application should continue to run after this error, it may be in an "
         "unstable state, so it is recommended that you restart the application."
     )
     self.label2 = QLabel(msg)
     self.label2.setWordWrap(True)
     self.verticalLayout.addWidget(self.label2)
     self.horizontalLayout = QHBoxLayout()
     self.horizontalLayout.addItem(horizontalSpacer())
     self.dontSendButton = QPushButton(self)
     self.dontSendButton.setText(tr("Close"))
     self.dontSendButton.setMinimumSize(QSize(110, 0))
     self.horizontalLayout.addWidget(self.dontSendButton)
     self.sendButton = QPushButton(self)
     self.sendButton.setText(tr("Go to Github"))
     self.sendButton.setMinimumSize(QSize(110, 0))
     self.sendButton.setDefault(True)
     self.horizontalLayout.addWidget(self.sendButton)
     self.verticalLayout.addLayout(self.horizontalLayout)
Exemplo n.º 30
0
    def __init__(self, map, blob, x, y, parent=None):
        super(QtCrackWidget, self).__init__(parent)

        self.setStyleSheet("background-color: rgb(60,60,65); color: white")

        self.qimg_cropped = utils.cropQImage(map, blob.bbox)
        arr = utils.qimageToNumpyArray(self.qimg_cropped)
        self.input_arr = rgb2gray(arr) * 255
        self.tolerance = 20
        self.blob = blob
        self.xmap = x
        self.ymap = y
        self.qimg_crack = QImage(self.qimg_cropped.width(), self.qimg_cropped.height(), QImage.Format_RGB32)
        self.qimg_crack.fill(qRgb(0, 0, 0))

        self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.setFixedWidth(400)
        self.setFixedHeight(400)

        SLIDER_WIDTH = 200
        IMAGEVIEWER_SIZE = 300  # SIZE x SIZE

        self.sliderTolerance = QSlider(Qt.Horizontal)
        self.sliderTolerance.setFocusPolicy(Qt.StrongFocus)
        self.sliderTolerance.setMinimumWidth(SLIDER_WIDTH)
        self.sliderTolerance.setMinimum(1)
        self.sliderTolerance.setMaximum(100)
        self.sliderTolerance.setValue(self.tolerance)
        self.sliderTolerance.setTickInterval(5)
        self.sliderTolerance.setAutoFillBackground(True)
        self.sliderTolerance.valueChanged.connect(self.sliderToleranceChanged)

        self.lblTolerance = QLabel("Tolerance: 20")
        self.lblTolerance.setAutoFillBackground(True)
        str = "Tolerance {}".format(self.tolerance)
        self.lblTolerance.setText(str)

        layoutTolerance = QHBoxLayout()
        layoutTolerance.addWidget(self.lblTolerance)
        layoutTolerance.addWidget(self.sliderTolerance)

        self.viewerplus = QtImageViewerPlus()
        self.viewerplus.disableScrollBars()
        self.viewerplus.setFixedWidth(IMAGEVIEWER_SIZE)
        self.viewerplus.setFixedHeight(IMAGEVIEWER_SIZE)

        self.btnCancel = QPushButton("Cancel")
        self.btnCancel.setAutoFillBackground(True)

        self.btnApply = QPushButton("Apply")
        self.btnApply.setAutoFillBackground(True)

        layoutButtons = QHBoxLayout()
        layoutButtons.addWidget(self.btnCancel)
        layoutButtons.addWidget(self.btnApply)

        layoutV = QVBoxLayout()
        layoutV.addLayout(layoutTolerance)
        layoutV.addWidget(self.viewerplus)
        layoutV.addLayout(layoutButtons)
        layoutV.setSpacing(10)
        self.setLayout(layoutV)

        self.viewerplus.setImage(self.qimg_cropped)
        self.preview()

        self.setAutoFillBackground(True)

        self.setWindowTitle("Crack")
Exemplo n.º 31
0
 def __InitView(self):
     # self.setFixedSize(640,480)
     # self.setFixedSize(480,410)
     self.setFixedSize(800, 618)
     self.setWindowTitle("Handwritten Digit Recognition Based on HOG-ELM")
     self.setWindowIcon(QIcon('ICON.ico'))
     main_layout = QHBoxLayout(self)
     main_layout.setSpacing(10)
     main_layout.addWidget(self.__paintBoard)
     self.font = QtGui.QFont()
     self.font.setFamily("Consolas")
     self.font.setPointSize(15)
     sub_layout = QVBoxLayout()
     sub_layout.setContentsMargins(10, 10, 10, 10)
     self.__btn_Clear = QPushButton("Clear Board")
     self.__btn_Clear.setParent(self)
     self.__btn_Clear.setFixedSize(146, 70)
     self.__btn_Clear.setFont(self.font)
     self.__btn_Clear.clicked.connect(self.__paintBoard.Clear)
     sub_layout.addWidget(self.__btn_Clear)
     self.__btn_Quit = QPushButton("Exit")
     self.__btn_Quit.setParent(self)
     self.__btn_Quit.setFixedSize(146, 70)
     self.__btn_Quit.setFont(self.font)
     self.__btn_Quit.clicked.connect(self.Quit)
     sub_layout.addWidget(self.__btn_Quit)
     self.__btn_Save = QPushButton("Save Board")
     self.__btn_Save.setParent(self)
     self.__btn_Save.setFixedSize(146, 70)
     self.__btn_Save.setFont(self.font)
     self.__btn_Save.clicked.connect(self.on_btn_Save_Clicked)
     sub_layout.addWidget(self.__btn_Save)
     self.__cbtn_Eraser = QCheckBox("Eraser")
     self.__cbtn_Eraser.setParent(self)
     self.__cbtn_Eraser.setFont(self.font)
     self.__cbtn_Eraser.clicked.connect(self.on_cbtn_Eraser_clicked)
     sub_layout.addWidget(self.__cbtn_Eraser)
     self.__label_result = QLabel(self)
     self.__label_result.setAlignment(Qt.AlignCenter)
     self.__label_result.setFixedWidth(146)
     self.__label_result.setFixedHeight(80)
     self.__label_result.setFrameStyle(PyQt5.QtWidgets.QFrame.Box)
     self.__label_result.setFrameShadow(PyQt5.QtWidgets.QFrame.Raised)
     self.__label_result.setLineWidth(6)
     self.__label_result.setMidLineWidth(5)
     self.__label_result.setStyleSheet('background-color: rgb(255,123,100)')
     sub_layout.addWidget(self.__label_result)
     self.__btn_Recognize = QPushButton("Recognition")
     self.__btn_Recognize.setParent(self)
     self.__btn_Recognize.setFixedSize(146, 70)
     self.__btn_Recognize.setFont(self.font)
     self.__btn_Recognize.clicked.connect(self.on_btn_Recognize_clicked)
     sub_layout.addWidget(self.__btn_Recognize)
     self.__label_timage = QLabel(self)
     self.__label_timage.setAlignment(Qt.AlignCenter)
     self.__label_timage.setFixedWidth(146)
     self.__label_timage.setFixedHeight(80)
     self.__label_timage.setFrameStyle(PyQt5.QtWidgets.QFrame.Box)
     self.__label_timage.setFrameShadow(PyQt5.QtWidgets.QFrame.Raised)
     self.__label_timage.setLineWidth(6)
     self.__label_timage.setMidLineWidth(5)
     self.__label_timage.setStyleSheet('background-color: rgb(125,143,50)')
     sub_layout.addWidget(self.__label_timage)
     self.__btn_Random = QPushButton("RandomDigit \nFrom TestSet")
     self.__btn_Random.setParent(self)
     self.__btn_Random.setFixedSize(146, 70)
     self.font.setPointSize(13)
     self.__btn_Random.setFont(self.font)
     self.__btn_Random.clicked.connect(self.on_btn_RandomDigit_Clicked)
     sub_layout.addWidget(self.__btn_Random)
     main_layout.addLayout(sub_layout)
Exemplo n.º 32
0
class PhotoWidget(QFrame):
    """
    Миниатюра изображения с подписью.

    :var change_tags: сигнал для запуска редактора тегов
    """

    change_tags = pyqtSignal(str)

    def __init__(self, parent: QWidget, filename: str):
        super().__init__(parent)

        self.filename = filename
        #self.setFrameStyle(QFrame.Panel)
        self.setFixedSize(160, 160)

        self.preview_label = QLabel("", parent=self)
        self.preview_label.setPixmap(
            QPixmap(filename).scaled(128,
                                     128,
                                     aspectRatioMode=Qt.KeepAspectRatio))
        self.preview_label.setAlignment(Qt.AlignCenter)
        self.preview_label.setGeometry(16, 4, 128, 128)

        self.text_label = QLabel(os.path.split(filename)[-1], parent=self)
        self.text_label.setAlignment(Qt.AlignCenter)
        self.text_label.setGeometry(4, 132, 152, 28)

    def mousePressEvent(self, event: QMouseEvent) -> None:
        """
        Обработка событий от мыши - открытие изображения и меню действий.

        :param event: событие мыши
        :type event: QMouseEvent
        """
        if event.button() == Qt.LeftButton:
            self.openImage()
        elif event.button() == Qt.RightButton:
            self.list_menu = QMenu()
            menu_item = self.list_menu.addAction("Open image")
            menu_item.triggered.connect(self.openImage)
            menu_item = self.list_menu.addAction("Copy path")
            menu_item.triggered.connect(self.copyPath)
            menu_item = self.list_menu.addAction("Edit tags")
            menu_item.triggered.connect(self.editTags)
            self.list_menu.move(self.mapToGlobal(event.pos()))
            self.list_menu.show()

    def openImage(self) -> None:
        """
        Открытие изображения во внешнем приложении.
        """
        if platform.system() == 'Darwin':  # macOS
            subprocess.call(('open', self.filename))
        elif platform.system() == 'Windows':  # Windows
            os.startfile(self.filename)
        else:  # linux variants
            subprocess.call(('xdg-open', self.filename))

    def copyPath(self) -> None:
        """
        Копирование пути до изображения в буфер обмена.
        """
        clipboard = QApplication.clipboard()
        clipboard.setText(os.path.abspath(self.filename))
        QApplication.sendEvent(clipboard, QEvent(QEvent.Clipboard))

    def editTags(self) -> None:
        """
        Вызов редактора тегов.
        """
        self.change_tags.emit(self.filename)
Exemplo n.º 33
0
    def initUI(self):
        '''
        # 标签1
        lb1 = QLabel("源目录", self)
        #lb1.move(20,30)
        # 标签2
        lb2=QLabel("目标目录",self)
        #lb2.move(20, 70)
        # 输入框1
        self.ledit1 = QLineEdit(self)
        #self.ledit1.setGeometry(QtCore.QRect(110, 30, 200, 30))
        # 输入框2
        self.ledit2 = QLineEdit(self)
        #self.ledit2.setGeometry(QtCore.QRect(110, 70, 200, 30))
        # 按钮1
        btn_start=QPushButton('开始处理',self)
        #btn_start.move(20,120)
        btn_start.setToolTip('<b>开始合并CMO的版本</b>')
        btn_start.clicked.connect(self.process_dir)
        #按钮2
        btn_quit = QPushButton('退出', self)
        #btn_quit.move(220, 120)
        btn_quit.setToolTip('<b>退出程序</b>')
        btn_quit.clicked.connect(qApp.quit)
        '''

        srcdir = QLabel('源目录')
        destdir = QLabel('目标目录')

        self.srcdir_edit = QLineEdit()
        self.destdir_edit = QLineEdit()

        ok_button = QPushButton("开始处理")
        ok_button.setToolTip('<b>开始合并CMO的版本</b>')
        ok_button.clicked.connect(self.process_dir)
        quit_button = QPushButton("退出")
        quit_button.setToolTip('<b>退出程序</b>')
        quit_button.clicked.connect(qApp.quit)

        log_lab = QLabel('日志信息')
        self.log_edit = QTextEdit()

        grid = QGridLayout()
        grid.setSpacing(10)

        grid.addWidget(srcdir, 1, 0)
        grid.addWidget(self.srcdir_edit, 1, 1, 2, 1)

        grid.addWidget(destdir, 3, 0)
        grid.addWidget(self.destdir_edit, 3, 1, 2, 1)

        grid.addWidget(quit_button, 5, 0, 1, 1)
        grid.addWidget(ok_button, 5, 1, 1, 1)

        grid.addWidget(log_lab, 7, 0, 1, 1)
        grid.addWidget(self.log_edit, 7, 1, 1, 1)
        self.setLayout(grid)

        self.setGeometry(300, 300, 550, 450)
        self.setWindowTitle("版本预处理")
        self.setWindowIcon(QtGui.QIcon('./download.png'))
        self.show()
    def handle_scan_click(self):
        """
        Handle scan button action event.
        Responsible for enabling waiting bar
        """
        label = QLabel(self)
        label.setText("SEARCHING")
        self.setDisabled(True)

        label_width = 500
        label_height = 100
        label_x_pos = self.size().width() // 2 - label_width // 2
        label_y_pos = self.size().height() // 2 - label_height // 2

        movie = QMovie("ajax-loader.gif")
        label.setGeometry(label_x_pos, label_y_pos, label_width, label_height)
        label.setFrameStyle(Qt.FramelessWindowHint)
        label.setMovie(movie)
        label.show()
        movie.setScaledSize(label.size())
        movie.start()

        self.extract_data_from_fields()
Exemplo n.º 35
0
 def getCaseId(self):
     self.caseLabel = QLabel(self)
     self.caseLabel.setText('CaseId:')
     self.lineCase = QLineEdit(self)
     self.lineCase.move(480, 70)
     self.caseLabel.move(420, 70)
Exemplo n.º 36
0
class NewCase(QMainWindow):
    """
    This class is a subpart of main window.
    The purpose of this class is to register a new case and
    save it in Firebase Database.

    After selecting the image you'll see in left side of window.
    If you are able to see image that means algo is able to find
    facial points in image. Otherwise you'll get error.

    If you encounter any error while saving the image, check the logs
    which are being printed.
    """
    def __init__(self, parent=None):
        """
        We are initializing few things we would need.
            name -> Name of person whose case has to be registered.
            age -> Age of the person
            mob -> Mobile number that will be contacted after the person is found.
            father_name -> Father's name of the person
            image -> image of the person
        """
        super().__init__().__init__(parent)
        self.caseId = ""
        self.email = ""
        self.title = "Register New Case"
        self.name = ""
        self.age = ""
        self.mob = ""
        self.father_name = ""
        self.image = None
        self.encoded_image = None
        self.key_points = None
        self.initialize()

    def initialize(self):
        """
        This method contains button to select the image and
        also register the case.

        The select image button is connected to openFileNameDialog method.

        The save button is connected to save method (within the class).

        -> If you are chaning the window size make sure to align the buttons
            correctly.
        """
        self.setFixedSize(600, 400)
        self.setWindowTitle(self.title)

        uploadImageBT = QPushButton("Select Photo", self)
        uploadImageBT.move(400, 20)
        uploadImageBT.clicked.connect(self.openFileNameDialog)

        saveBT = QPushButton("Save ", self)
        saveBT.move(400, 350)
        saveBT.clicked.connect(self.save)

        self.getCaseId()
        self.getName()
        self.getAge()
        self.getFName()
        self.getMob()
        self.getEmail()
        self.show()


    def getName(self):
        """
        This method reads the input name from text field in GUI.
        """
        self.nameLabel = QLabel(self)
        self.nameLabel.setText('Name:')
        self.lineName = QLineEdit(self)
        self.lineName.move(480, 110)
        self.nameLabel.move(420, 110)
        # self.line.resize(200, 32)

    def getCaseId(self):
        self.caseLabel = QLabel(self)
        self.caseLabel.setText('CaseId:')
        self.lineCase = QLineEdit(self)
        self.lineCase.move(480, 70)
        self.caseLabel.move(420, 70)


    def getAge(self):
        """
        This method reads the age from text field in GUI.
        """
        self.ageLabel = QLabel(self)
        self.ageLabel.setText('Age:')
        self.lineAge = QLineEdit(self)
        self.lineAge.move(480, 150)
        self.ageLabel.move(420, 150)

    def getFName(self):
        """
        This method reads Father's name from text field in GUI.
        """
        self.FnameLabel = QLabel(self)
        self.FnameLabel.setText('Father\'s\n Name:')
        self.lineFName = QLineEdit(self)
        self.lineFName.move(480, 190)
        self.FnameLabel.move(420, 190)

    def getMob(self):
        """
        This method reads mob number from text field in GUI.
        """
        self.mobLabel = QLabel(self)
        self.mobLabel.setText('Mobile:')
        self.lineMob = QLineEdit(self)
        self.lineMob.move(480, 230)
        self.mobLabel.move(420, 230)

    def getEmail(self):
        self.emailLabel = QLabel(self)
        self.emailLabel.setText('Email:')
        self.lineEmail = QLineEdit(self)
        self.lineEmail.move(480, 270)
        self.emailLabel.move(420, 270)

    def read_image(self, image_path: str):
        """
        Takes image URL as input and returns image.

        Parameters
        ----------
        image_path: str
            The path of image on local system.

        Returns
        -------
            PIL JPEG Image
        """
        return Image.open(image_path)

    def get_base64_form(self) -> str:
        """
        This method converts the image read by read_image method to string.

        Returns
        -------
        img_str: str
            Image is convterted in base64.
        """
        buff = io.BytesIO()
        self.image.save(buff, format="JPEG")
        img_str = base64.b64encode(buff.getvalue())
        return img_str

    def get_key_points(self) -> list:
        """
        This method passes the base64 form iamge to get facialkey points.

        Returns
        -------
         list
        """
        return face_encoding.get_key_points(self.encoded_image)

    def openFileNameDialog(self):
        """
        This method is triggered on button click to select image.

        When an image is selected its local URL is captured.
        After which it is passed through read_image method.
        Then it is converted to base64 format and facial keypoints are
        generated for it.

        If keypoints are not found in the image then you'll get a dialogbox.
        """
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getOpenFileName(self, "QFileDialog.getOpenFileName()", "", "jpg file (*.jpg)", options=options)  # nopep8
        fileName = cv2.imread(fileName)
        image = cv2.resize(fileName,(200,200),interpolation=cv2.INTER_AREA) 
        cv2.imwrite("file.jpg",image);
        fileName = "file.jpg"	 	
        if fileName:
            self.image = self.read_image(fileName)
            self.encoded_image = self.get_base64_form()
            self.key_points = self.get_key_points()
            if self.key_points != []:
                label = QLabel(self)
                pixmap = QPixmap(fileName)
                pixmap = pixmap.scaled(280, 350)
                label.setPixmap(pixmap)
                label.resize(280, 350)
                label.move(10, 10)
                label.show()
            else:
                QMessageBox.about(self,
                                  "Error",
                                  "Face not detected")

    def check_entries(self, mob: str, age: str, name: str, father_name: str, caseId: str, email: str) -> bool:
        """
        A check to make sure empty fields are not saved.
        A case will be uniquely identified by these fields. 
        """
        if mob != "" and age != "" and name != "" and father_name != "" and caseId != "" and email != "":
            return True
        else:
            return False

    def save(self):
        """
        Save method is triggered with save button on GUI.
       
        All the parameters are passed to a db methods whose task is to save
        them in db.

        If the save operation is successful then you'll get True as output and
        a dialog message will be displayed other False will be returned and
        you'll get appropriate message.

        """
        self.mob = self.lineMob.text()
        self.age = self.lineAge.text()
        self.name = self.lineName.text()
        self.caseId = self.lineCase.text()
        self.email = self.lineEmail.text()
        self.father_name = self.lineFName.text()
        if self.check_entries(self.mob, self.age, self.name, self.father_name,self.caseId,self.email):
            self.key_points = face_encoding.encode(self.key_points)
            if db_operations.add_to_pending(self.key_points,
            	                            self.caseId,
                                            self.name,
                                            self.father_name,
                                            self.age,
                                            self.mob,
                                            self.email) is True:
                QMessageBox.about(self, "Success", "Image is added to DB. \n\
                                You can close the window")
                sendCaseRegistrationEmail(self.caseId,self.father_name,self.email)
                sendCaseRegistrationMessage(self.caseId,self.father_name,self.mob)
            else:
                QMessageBox.about(self, "Error", "Something went wrong. \
                                Please try again")
        else:
            QMessageBox.about(self, "Error", "Please fill all entries")
Exemplo n.º 37
0
 def getEmail(self):
     self.emailLabel = QLabel(self)
     self.emailLabel.setText('Email:')
     self.lineEmail = QLineEdit(self)
     self.lineEmail.move(480, 270)
     self.emailLabel.move(420, 270)
Exemplo n.º 38
0
class _CrashDialog(QDialog):
    """Dialog which gets shown after there was a crash.

    Attributes:
        These are just here to have a static reference to avoid GCing.
        _vbox: The main QVBoxLayout
        _lbl: The QLabel with the static text
        _debug_log: The QTextEdit with the crash information
        _btn_box: The QDialogButtonBox containing the buttons.
        _url: Pastebin URL QLabel.
        _crash_info: A list of tuples with title and crash information.
        _paste_client: A PastebinClient instance to use.
        _pypi_client: A PyPIVersionClient instance to use.
        _paste_text: The text to pastebin.
    """
    def __init__(self, debug, parent=None):
        """Constructor for CrashDialog.

        Args:
            debug: Whether --debug was given.
        """
        super().__init__(parent)
        # We don't set WA_DeleteOnClose here as on an exception, we'll get
        # closed anyways, and it only could have unintended side-effects.
        self._crash_info: List[Tuple[str, str]] = []
        self._btn_box = None
        self._paste_text = None
        self.setWindowTitle("Whoops!")
        self.resize(QSize(640, 600))
        self._vbox = QVBoxLayout(self)

        http_client = httpclient.HTTPClient()
        self._paste_client = pastebin.PastebinClient(http_client, self)
        self._pypi_client = autoupdate.PyPIVersionClient(self)
        self._paste_client.success.connect(self.on_paste_success)
        self._paste_client.error.connect(self.show_error)

        self._init_text()

        self._init_contact_input()

        info = QLabel("What were you doing when this crash/bug happened?")
        self._vbox.addWidget(info)
        self._info = QTextEdit()
        self._info.setTabChangesFocus(True)
        self._info.setAcceptRichText(False)
        self._info.setPlaceholderText("- Opened http://www.example.com/\n"
                                      "- Switched tabs\n"
                                      "- etc...")
        self._vbox.addWidget(self._info, 5)

        self._vbox.addSpacing(15)
        self._debug_log = QTextEdit()
        self._debug_log.setTabChangesFocus(True)
        self._debug_log.setAcceptRichText(False)
        self._debug_log.setLineWrapMode(QTextEdit.NoWrap)
        self._debug_log.hide()
        self._fold = miscwidgets.DetailFold("Show log", self)
        self._fold.toggled.connect(self._debug_log.setVisible)
        if debug:
            self._fold.toggle()
        self._vbox.addWidget(self._fold)
        self._vbox.addWidget(self._debug_log, 10)
        self._vbox.addSpacing(15)

        self._init_checkboxes()
        self._init_info_text()
        self._init_buttons()

    def keyPressEvent(self, e):
        """Prevent closing :report dialogs when pressing <Escape>."""
        if config.val.input.escape_quits_reporter or e.key() != Qt.Key_Escape:
            super().keyPressEvent(e)

    def __repr__(self):
        return utils.get_repr(self)

    def _init_contact_input(self):
        """Initialize the widget asking for contact info."""
        contact = QLabel("I'd like to be able to follow up with you, to keep "
                         "you posted on the status of this crash and get more "
                         "information if I need it - how can I contact you?")
        contact.setWordWrap(True)
        self._vbox.addWidget(contact)
        self._contact = QTextEdit()
        self._contact.setTabChangesFocus(True)
        self._contact.setAcceptRichText(False)
        try:
            try:
                info = configfiles.state['general']['contact-info']
            except KeyError:
                self._contact.setPlaceholderText("Mail or IRC nickname")
            else:
                self._contact.setPlainText(info)
        except Exception:
            log.misc.exception("Failed to get contact information!")
            self._contact.setPlaceholderText("Mail or IRC nickname")
        self._vbox.addWidget(self._contact, 2)

    def _init_text(self):
        """Initialize the main text to be displayed on an exception.

        Should be extended by subclasses to set the actual text.
        """
        self._lbl = QLabel()
        self._lbl.setWordWrap(True)
        self._lbl.setOpenExternalLinks(True)
        self._lbl.setTextInteractionFlags(Qt.LinksAccessibleByMouse)
        self._vbox.addWidget(self._lbl)

    def _init_checkboxes(self):
        """Initialize the checkboxes."""

    def _init_buttons(self):
        """Initialize the buttons."""
        self._btn_box = QDialogButtonBox()
        self._vbox.addWidget(self._btn_box)

        self._btn_report = QPushButton("Report")
        self._btn_report.setDefault(True)
        self._btn_report.clicked.connect(self.on_report_clicked)
        self._btn_box.addButton(self._btn_report, QDialogButtonBox.AcceptRole)

        self._btn_cancel = QPushButton("Don't report")
        self._btn_cancel.setAutoDefault(False)
        self._btn_cancel.clicked.connect(self.finish)
        self._btn_box.addButton(self._btn_cancel, QDialogButtonBox.RejectRole)

    def _init_info_text(self):
        """Add an info text encouraging the user to report crashes."""
        info_label = QLabel("<br/>There is currently a big backlog of crash "
                            "reports. Thus, it might take a while until your "
                            "report is seen.<br/>A new tool allowing for more "
                            "automation will fix this, but is not ready yet "
                            "at this point.")
        info_label.setWordWrap(True)
        self._vbox.addWidget(info_label)

    def _gather_crash_info(self):
        """Gather crash information to display.

        Args:
            pages: A list of lists of the open pages (URLs as strings)
            cmdhist: A list with the command history (as strings)
            exc: An exception tuple (type, value, traceback)
        """
        try:
            launch_time = objects.qapp.launch_time.ctime()
            crash_time = datetime.datetime.now().ctime()
            text = 'Launch: {}\nCrash: {}'.format(launch_time, crash_time)
            self._crash_info.append(('Timestamps', text))
        except Exception:
            self._crash_info.append(("Launch time", traceback.format_exc()))
        try:
            self._crash_info.append(("Version info", version.version_info()))
        except Exception:
            self._crash_info.append(("Version info", traceback.format_exc()))
        try:
            self._crash_info.append(
                ("Config", config.instance.dump_userconfig()))
        except Exception:
            self._crash_info.append(("Config", traceback.format_exc()))
        try:
            self._crash_info.append(("Environment", _get_environment_vars()))
        except Exception:
            self._crash_info.append(("Environment", traceback.format_exc()))

    def _set_crash_info(self):
        """Set/update the crash info."""
        self._crash_info = []
        self._gather_crash_info()
        chunks = []
        for (header, body) in self._crash_info:
            if body is not None:
                h = '==== {} ===='.format(header)
                chunks.append('\n'.join([h, body]))
        text = '\n\n'.join(chunks)
        self._debug_log.setText(text)

    def _get_error_type(self):
        """Get the type of the error we're reporting."""
        raise NotImplementedError

    def _get_paste_title_desc(self):
        """Get a short description of the paste."""
        return ''

    def _get_paste_title(self):
        """Get a title for the paste."""
        desc = self._get_paste_title_desc()
        title = "qute {} {}".format(qutebrowser.__version__,
                                    self._get_error_type())
        if desc:
            title += ' {}'.format(desc)
        return title

    def _save_contact_info(self):
        """Save the contact info to disk."""
        try:
            info = self._contact.toPlainText()
            configfiles.state['general']['contact-info'] = info
        except Exception:
            log.misc.exception("Failed to save contact information!")

    def report(self, *, info=None, contact=None):
        """Paste the crash info into the pastebin.

        If info/contact are given as arguments, they override the values
        entered in the dialog.
        """
        lines = []
        lines.append("========== Report ==========")
        lines.append(info or self._info.toPlainText())
        lines.append("========== Contact ==========")
        lines.append(contact or self._contact.toPlainText())
        lines.append("========== Debug log ==========")
        lines.append(self._debug_log.toPlainText())
        self._paste_text = '\n\n'.join(lines)
        try:
            user = getpass.getuser()
        except Exception:
            log.misc.exception("Error while getting user")
            user = '******'
        try:
            # parent: https://p.cmpl.cc/90286958
            self._paste_client.paste(user,
                                     self._get_paste_title(),
                                     self._paste_text,
                                     parent='90286958')
        except Exception as e:
            log.misc.exception("Error while paste-binning")
            exc_text = '{}: {}'.format(e.__class__.__name__, e)
            self.show_error(exc_text)

    @pyqtSlot()
    def on_report_clicked(self):
        """Report and close dialog if report button was clicked."""
        self._btn_report.setEnabled(False)
        self._btn_cancel.setEnabled(False)
        self._btn_report.setText("Reporting...")
        self.report()

    @pyqtSlot()
    def on_paste_success(self):
        """Get the newest version from PyPI when the paste is done."""
        self._pypi_client.success.connect(self.on_version_success)
        self._pypi_client.error.connect(self.on_version_error)
        self._pypi_client.get_version()

    @pyqtSlot(str)
    def show_error(self, text):
        """Show a paste error dialog.

        Args:
            text: The paste text to show.
        """
        error_dlg = ReportErrorDialog(text, self._paste_text, self)
        error_dlg.finished.connect(self.finish)
        error_dlg.show()

    @pyqtSlot(str)
    def on_version_success(self, newest):
        """Called when the version was obtained from self._pypi_client.

        Args:
            newest: The newest version as a string.
        """
        new_version = utils.VersionNumber.parse(newest)
        cur_version = utils.VersionNumber.parse(qutebrowser.__version__)
        lines = ['The report has been sent successfully. Thanks!']
        if new_version > cur_version:
            lines.append("<b>Note:</b> The newest available version is v{}, "
                         "but you're currently running v{} - please "
                         "update!".format(newest, qutebrowser.__version__))
        text = '<br/><br/>'.join(lines)
        msgbox.information(self,
                           "Report successfully sent!",
                           text,
                           on_finished=self.finish,
                           plain_text=False)

    @pyqtSlot(str)
    def on_version_error(self, msg):
        """Called when the version was not obtained from self._pypi_client.

        Args:
            msg: The error message to show.
        """
        lines = ['The report has been sent successfully. Thanks!']
        lines.append(
            "There was an error while getting the newest version: "
            "{}. Please check for a new version on "
            "<a href=https://www.qutebrowser.org/>qutebrowser.org</a> "
            "by yourself.".format(msg))
        text = '<br/><br/>'.join(lines)
        msgbox.information(self,
                           "Report successfully sent!",
                           text,
                           on_finished=self.finish,
                           plain_text=False)

    @pyqtSlot()
    def finish(self):
        """Save contact info and close the dialog."""
        self._save_contact_info()
        self.accept()
Exemplo n.º 39
0
class VideoWindow(QMainWindow):
    def __init__(self, parent=None):
        super(VideoWindow, self).__init__(parent)
        self.setWindowTitle("ONI Player")
        self.setWindowIcon(QIcon('images/play.png'))
        self.vsource = None

        class MediaPlayer(QMediaPlayer):
            def __init__(self, parent=None, flags=QMediaPlayer.VideoSurface):
                super(MediaPlayer, self).__init__(parent)
                self.parent = parent

            def frame_step(self, direction):
                frames = list(map(round, self.parent.vsource.track.timecodes))
                if 0 < self.position() < max(frames):
                    dif = [abs(self.position() - x) for x in frames]
                    self.setPosition(frames[dif.index(min(dif)) + direction])

        self.colorMediaPlayer = MediaPlayer(parent=self)
        self.depthMediaPlayer = MediaPlayer(parent=self)

        self.colorVideoWidget = QVideoWidget()
        self.depthVideoWidget = QVideoWidget()

        # spacers for control panel
        self.leftSpacerItem = QSpacerItem(10, 10, QSizePolicy.Expanding,
                                          QSizePolicy.Minimum)
        self.rightSpacerItem = QSpacerItem(10, 10, QSizePolicy.Expanding,
                                           QSizePolicy.Minimum)

        # buttom for control panel
        self.backButton = QPushButton()
        self.backButton.setEnabled(False)
        self.backButton.setIcon(self.style().standardIcon(
            QStyle.SP_MediaSeekBackward))
        self.backButton.clicked.connect(lambda: self.prev_next_frame(-1))
        self.backButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Minimum)

        self.playButton = QPushButton()
        self.playButton.setEnabled(False)
        self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.playButton.clicked.connect(self.play)
        self.playButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Minimum)

        self.forwardButton = QPushButton()
        self.forwardButton.setEnabled(False)
        self.forwardButton.setIcon(self.style().standardIcon(
            QStyle.SP_MediaSeekForward))
        self.forwardButton.clicked.connect(lambda: self.prev_next_frame(1))
        self.forwardButton.setSizePolicy(QSizePolicy.Fixed,
                                         QSizePolicy.Minimum)

        self.positionSlider = QSlider(Qt.Horizontal)
        self.positionSlider.setRange(0, 0)
        self.positionSlider.sliderMoved.connect(self.setPosition)

        self.errorLabel = QLabel()
        self.errorLabel.setSizePolicy(QSizePolicy.Preferred,
                                      QSizePolicy.Maximum)
        self.colorLabel = QLabel('Color stream')
        self.depthLabel = QLabel('Depth stream')
        self.hframe = QFrame(self)
        self.hframe.setFrameShape(QFrame.HLine)
        self.hframe.setFrameShadow(QFrame.Raised)
        # self.hframe.setLineWidth(1)

        # Create new action
        openAction = QAction(QIcon('open.png'), '&Open', self)
        openAction.setShortcut('Ctrl+O')
        openAction.setStatusTip('Open movie')
        openAction.triggered.connect(self.openFile)

        # Create exit action
        exitAction = QAction(QIcon('exit.png'), '&Exit', self)  # png!!!
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(self.exitCall)

        # Create menu bar and add action
        menuBar = self.menuBar()
        fileMenu = menuBar.addMenu('&File')
        fileMenu.addAction(openAction)
        fileMenu.addAction(exitAction)

        # Create a widget for window contents
        wid = QWidget(self)
        self.setCentralWidget(wid)

        # Create layouts to place inside widget
        controlLayout = QHBoxLayout()
        controlLayout.addSpacerItem(self.leftSpacerItem)
        controlLayout.addWidget(self.backButton)
        controlLayout.addWidget(self.playButton)
        controlLayout.addWidget(self.forwardButton)
        controlLayout.addSpacerItem(self.rightSpacerItem)

        self.videoLayout = QGridLayout()
        self.videoLayout.setSpacing(10)
        self.videoLayout.addWidget(self.colorLabel, 0, 0, Qt.AlignCenter)
        self.videoLayout.addWidget(self.depthLabel, 0, 1, Qt.AlignCenter)
        self.videoLayout.addWidget(self.colorVideoWidget, 1, 0)
        self.videoLayout.addWidget(self.depthVideoWidget, 1, 1)

        layout = QVBoxLayout()
        layout.addLayout(self.videoLayout)
        layout.addWidget(self.positionSlider)
        layout.addLayout(controlLayout)
        layout.addWidget(self.hframe)
        layout.addWidget(self.errorLabel)

        # Set widget to contain window contents
        wid.setLayout(layout)

        self.colorMediaPlayer.setVideoOutput(self.colorVideoWidget)
        self.colorMediaPlayer.stateChanged.connect(self.mediaStateChanged)
        self.colorMediaPlayer.positionChanged.connect(self.positionChanged)
        self.colorMediaPlayer.durationChanged.connect(self.durationChanged)
        self.colorMediaPlayer.error.connect(self.handleError)

        self.depthMediaPlayer.setVideoOutput(self.depthVideoWidget)
        self.depthMediaPlayer.stateChanged.connect(self.mediaStateChanged)
        self.depthMediaPlayer.positionChanged.connect(self.positionChanged)
        self.depthMediaPlayer.durationChanged.connect(self.durationChanged)
        self.depthMediaPlayer.error.connect(self.handleError)

    def openFile(self):
        fileName, _ = QFileDialog.getOpenFileName(self, "Open oni file", '',
                                                  '*.oni', QDir.homePath())
        self.errorLabel.setText("Processing of ONI file. Please wait.")
        path_to_color_avi = os.path.join(os.getcwd(), 'color.avi')
        path_to_depth_avi = os.path.join(os.getcwd(), 'depth.avi')
        if fileName != '':
            print(self.errorLabel.text())
            oni_converter(fileName)
            if os.path.isfile('color.avi') and os.path.isfile('depth.avi'):
                self.errorLabel.setText(
                    "ONI file has been processed successfully.")
            self.colorMediaPlayer.setMedia(
                QMediaContent(QUrl.fromLocalFile(path_to_color_avi)))
            self.depthMediaPlayer.setMedia(
                QMediaContent(QUrl.fromLocalFile(path_to_depth_avi)))
            self.playButton.setEnabled(True)
            self.vsource = ffms2.VideoSource('color.avi')

    def exitCall(self):
        sys.exit(app.exec_())

    def play(self):
        if self.colorMediaPlayer.state() == QMediaPlayer.PlayingState:
            self.colorMediaPlayer.pause()
            self.depthMediaPlayer.pause()
        else:
            self.errorLabel.setText('')
            self.colorMediaPlayer.play()
            self.depthMediaPlayer.play()

    def prev_next_frame(self, direction):
        if self.colorMediaPlayer.state() == QMediaPlayer.PausedState:
            self.colorMediaPlayer.frame_step(direction)
            self.depthMediaPlayer.frame_step(direction)

    def mediaStateChanged(self, state):
        if self.colorMediaPlayer.state() == QMediaPlayer.PlayingState:
            self.playButton.setIcon(self.style().standardIcon(
                QStyle.SP_MediaPause))
            self.backButton.setEnabled(False)
            self.forwardButton.setEnabled(False)
        else:
            self.playButton.setIcon(self.style().standardIcon(
                QStyle.SP_MediaPlay))
            self.backButton.setEnabled(True)
            self.forwardButton.setEnabled(True)

    def positionChanged(self, position):
        self.positionSlider.setValue(position)

    def durationChanged(self, duration):
        self.positionSlider.setRange(0, duration)

    def setPosition(self, position):
        self.colorMediaPlayer.setPosition(position)
        self.depthMediaPlayer.setPosition(position)

    def handleError(self):
        self.playButton.setEnabled(False)
        self.errorLabel.setText("Error: " +
                                self.colorMediaPlayer.errorString())
Exemplo n.º 40
0
class MarkWindow(QWidget):

    def __init__(self):
        super().__init__()

        # set exit button
        self.exit_button = QPushButton(self)
        self.exit_button.setIcon(QIcon("./icon/quit.png"))
        self.exit_button.setShortcut('Ctrl+Q')
        self.exit_button.setFixedHeight(32)
        self.exit_button.setFixedWidth(32)
        self.exit_button.setToolTip("Quit APP")
        self.exit_button.clicked.connect(qApp.quit)


        # set open button
        self.open_button = QPushButton(self)
        self.open_button.setIcon(QIcon("./icon/open.png"))
        self.open_button.setShortcut('Ctrl+O')
        self.open_button.setFixedHeight(32)
        self.open_button.setFixedWidth(32)
        self.open_button.setToolTip("Open Image")
        self.open_button.clicked.connect(self.open_image)
        self.image_name = ''

        # set save button
        self.save_button = QPushButton(self)
        self.save_button.setIcon(QIcon("./icon/save.png"))
        self.save_button.setShortcut('Ctrl+S')
        self.save_button.setFixedHeight(32)
        self.save_button.setFixedWidth(32)
        self.save_button.setToolTip("Save Image")
        self.save_button.clicked.connect(self.save_image)


        # set save_as button
        self.save_as_button = QPushButton(self)
        self.save_as_button.setIcon(QIcon("./icon/save_as.png"))
        self.save_as_button.setShortcut('Ctrl+S')
        self.save_as_button.setFixedHeight(32)
        self.save_as_button.setFixedWidth(32)
        self.save_as_button.setToolTip("Save As Image")
        self.save_as_button.clicked.connect(self.save_as_image)

        # set close button
        self.close_button = QPushButton(self)
        self.close_button.setIcon(QIcon("./icon/close.png"))
        self.close_button.setShortcut('Ctrl+E')
        self.close_button.setFixedHeight(32)
        self.close_button.setFixedWidth(32)
        self.close_button.setToolTip("Close Image")
        self.close_button.clicked.connect(self.close_image)

        # set draw rectangle button
        self.label_button = QPushButton(self)
        self.label_button.setIcon(QIcon("./icon/mark.png"))
        self.label_button.setShortcut('Ctrl+R')
        self.label_button.setFixedHeight(32)
        self.label_button.setFixedWidth(32)
        self.label_button.setToolTip("Draw Label")
        self.label_button.clicked.connect(self.draw_mark)

        # set hide mark button
        self.hide_mark_button = QPushButton(self)
        self.hide_mark_button.setIcon(QIcon("./icon/hide.png"))
        self.hide_mark_button.setShortcut('Ctrl+R')
        self.hide_mark_button.setFixedHeight(32)
        self.hide_mark_button.setFixedWidth(32)
        self.hide_mark_button.setToolTip("Hide Label")
        self.hide_mark_button.clicked.connect(self.hide_mark)

        # set up button
        self.up_button = QPushButton(self)
        self.up_button.setIcon(QIcon("./icon/up.png"))
        self.up_button.setShortcut('Ctrl+U')
        self.up_button.setFixedHeight(control_button_height)
        self.up_button.setFixedWidth(control_button_width)
        self.up_button.setToolTip("Up Camera")
        self.up_button.pressed.connect(self.up_pressed)
        self.up_button.released.connect(self.up_released)

        # set down button
        self.down_button = QPushButton(self)
        self.down_button.setIcon(QIcon("./icon/down.png"))
        self.down_button.setShortcut('Ctrl+D')
        self.down_button.setFixedHeight(control_button_height)
        self.down_button.setFixedWidth(control_button_width)
        self.down_button.setToolTip("Down Camera")
        self.down_button.pressed.connect(self.down_pressed)
        self.down_button.released.connect(self.down_released)
        self.image_name = ''

        # set left button
        self.left_button = QPushButton(self)
        self.left_button.setIcon(QIcon("./icon/left.png"))
        self.left_button.setShortcut('Ctrl+L')
        self.left_button.setFixedHeight(control_button_height)
        self.left_button.setFixedWidth(control_button_width)
        self.left_button.setToolTip("Ledt Camera")
        self.left_button.pressed.connect(self.left_pressed)
        self.left_button.released.connect(self.left_released)

        # set right button
        self.right_button = QPushButton(self)
        self.right_button.setIcon(QIcon("./icon/right.png"))
        self.right_button.setShortcut('Ctrl+R')
        self.right_button.setFixedHeight(control_button_height)
        self.right_button.setFixedWidth(control_button_width)
        self.right_button.setToolTip("Right Camera")
        self.right_button.pressed.connect(self.right_pressed)
        self.right_button.released.connect(self.right_released)

        # set focus near button
        self.focus_near_button = QPushButton(self)
        self.focus_near_button.setIcon(QIcon("./icon/focus_near.png"))
        self.focus_near_button.setShortcut('Ctrl+N')
        self.focus_near_button.setFixedHeight(control_button_height)
        self.focus_near_button.setFixedWidth(control_button_width)
        self.focus_near_button.setToolTip("Focus Near Image")
        self.focus_near_button.pressed.connect(self.focus_near_pressed)
        self.focus_near_button.released.connect(self.focus_near_released)

        # set focus far button
        self.focus_far_button = QPushButton(self)
        self.focus_far_button.setIcon(QIcon("./icon/focus_far.png"))
        self.focus_far_button.setShortcut('Ctrl+F')
        self.focus_far_button.setFixedHeight(control_button_height)
        self.focus_far_button.setFixedWidth(control_button_width)
        self.focus_far_button.setToolTip("Focus Far Image")
        self.focus_far_button.pressed.connect(self.focus_far_pressed)
        self.focus_far_button.released.connect(self.focus_far_released)

        # set zoom in button
        self.zoom_in_button = QPushButton(self)
        self.zoom_in_button.setIcon(QIcon("./icon/zoom_in.png"))
        self.zoom_in_button.setShortcut('Ctrl+Z+I')
        self.zoom_in_button.setFixedHeight(control_button_height)
        self.zoom_in_button.setFixedWidth(control_button_width)
        self.zoom_in_button.setToolTip("Zoom In Image")
        self.zoom_in_button.pressed.connect(self.zoom_in_pressed)
        self.zoom_in_button.released.connect(self.zoom_in_released)

        # set zoom out button
        self.zoom_out_button = QPushButton(self)
        self.zoom_out_button.setIcon(QIcon("./icon/zoom_out.png"))
        self.zoom_out_button.setShortcut('Ctrl+Z+O')
        self.zoom_out_button.setFixedHeight(control_button_height)
        self.zoom_out_button.setFixedWidth(control_button_width)
        self.zoom_out_button.setToolTip("Zoom Out Image")
        self.zoom_out_button.pressed.connect(self.zoom_out_pressed)
        self.zoom_out_button.released.connect(self.zoom_out_released)

        #thumbnail QLabel
        self.thumbnail_label = myLabel()
        self.thumbnail_label.clicked.connect(self.thumnail_clicked)

        self.video_panel = QLabel()
        self.video_panel.setFixedWidth(400)
        self.video_panel.setFixedHeight(400)
        self.video_panel.setScaledContents(True)
        # set zoom ratio
        self.zoom_ratio = 1

        self.h_layout_tool_bar = QHBoxLayout()
        self.h_layout_tool_bar.addWidget(self.exit_button)
        self.h_layout_tool_bar.addWidget(self.open_button)
        self.h_layout_tool_bar.addWidget(self.save_button)
        self.h_layout_tool_bar.addWidget(self.save_as_button)
        self.h_layout_tool_bar.addWidget(self.close_button)
        self.h_layout_tool_bar.addWidget(self.label_button)
        self.h_layout_tool_bar.addWidget(self.hide_mark_button)
        self.tool_bar = QWidget()
        self.tool_bar.setLayout(self.h_layout_tool_bar)
        self.tool_bar.setFixedHeight(50)

        self.h_layout_thumbnail = QHBoxLayout()
        self.h_layout_thumbnail.addWidget(self.thumbnail_label)
        self.thumbnail = QWidget()
        self.thumbnail.setLayout(self.h_layout_thumbnail)
        # global thumbnail_label_height
        # global thumbnail_label_width
        # self.thumbnail.setFixedHeight(thumbnail_label_height)
        # self.thumbnail.setFixedWidth(thumbnail_label_width)

        self.picture = ''
        self.original_picture = ''
        self.thumbnail_picture=''
        self.pixel_map = QPixmap()
        self.image_panel = ImageLabel()
        self.image_panel.setScaledContents(True)

        self.scroll_area = QScrollArea()
        self.scroll_area.setWidget(self.image_panel)
        self.scroll_area.setAlignment(Qt.AlignCenter)

        self.input_mark = QLineEdit()
        self.input_mark.setFixedHeight(30)
        self.input_mark.setAlignment(Qt.AlignCenter)

        self.h_layout_left_area = QVBoxLayout()
        self.h_layout_left_area.addWidget(self.tool_bar)
        self.h_layout_left_area.addWidget(self.scroll_area)
        self.h_layout_left_area.addWidget(self.input_mark)
        self.left_area = QWidget()
        self.left_area.setLayout(self.h_layout_left_area)

        self.h_layout_control_1 = QHBoxLayout()
        self.h_layout_control_1.addWidget(self.up_button)
        self.h_layout_control_1.addWidget(self.down_button)
        self.h_layout_control_1.addWidget(self.focus_near_button)
        self.h_layout_control_1.addWidget(self.focus_far_button)
        self.control_1 = QWidget()
        self.control_1.setLayout(self.h_layout_control_1)

        self.h_layout_control_2 = QHBoxLayout()
        self.h_layout_control_2.addWidget(self.left_button)
        self.h_layout_control_2.addWidget(self.right_button)
        self.h_layout_control_2.addWidget(self.zoom_in_button)
        self.h_layout_control_2.addWidget(self.zoom_out_button)
        self.control_2 = QWidget()
        self.control_2.setLayout(self.h_layout_control_2)

        self.h_layout_control_pannel = QVBoxLayout()
        self.h_layout_control_pannel.addWidget(self.control_1)
        self.h_layout_control_pannel.addWidget(self.control_2)
        self.h_layout_control_pannel.setAlignment(Qt.AlignCenter)
        self.control_pannel = QWidget()
        self.control_pannel.setLayout(self.h_layout_control_pannel)

        self.h_layout_video_frame = QHBoxLayout()
        self.h_layout_video_frame.addWidget(self.video_panel)
        self.h_layout_video_frame.setAlignment(Qt.AlignCenter)
        self.video_frame = QWidget()
        self.video_frame.setLayout(self.h_layout_video_frame)

        self.h_layout_right_area = QVBoxLayout()
        self.h_layout_right_area.addWidget(self.video_frame)
        self.h_layout_right_area.addWidget(self.control_pannel)
        self.right_area = QWidget()
        self.right_area.setLayout(self.h_layout_right_area)

        self.h_layout = QHBoxLayout()
        self.h_layout.addWidget(self.left_area)
        self.h_layout.addWidget(self.right_area)
        self.top_area = QWidget()
        self.top_area.setLayout(self.h_layout)

        self.v_layout = QVBoxLayout()
        self.v_layout.addWidget(self.top_area)
        self.v_layout.addWidget(self.thumbnail)
        self.setLayout(self.v_layout)

        self.setMouseTracking(False)
        self.setWindowIcon(QIcon('./icons/icon.png'))
        self.img_path = "result.jpg"

        self.mythread = VideoThread()
        self.mythread.signal.connect(self.show_video)

    def open_image(self, img_path, pkl_file_path):

        global all_point
        global all_mark_text
        global all_start_list
        print(len(all_point))
        if os.path.exists(pkl_file_path):
            pkl_file = open(pkl_file_path, 'rb')
            save_data = pickle.load(pkl_file)
            all_point = save_data[0]
            all_mark_text = save_data[1]
            all_start_list = save_data[2]
        else:
            all_point = []
            all_mark_text = []
            all_start_list = []

        self.picture = cv2.imread(img_path)
        self.original_picture = self.picture.copy()
        self.load_image(img_path)
        self.show_thumbnail_picture()

    def load_image(self, img_path):
        self.pixel_map.load(img_path)
        print("ok")
        global original_img_height, original_img_width
        original_img_width = self.pixel_map.width()
        original_img_height = self.pixel_map.height()
        self.image_panel.resize(self.pixel_map.width(), self.pixel_map.height())
        self.image_panel.setPixmap(self.pixel_map)
        self.image_panel.setAlignment(Qt.AlignCenter)
        self.thumbnail_picture = self.picture.copy()
        self.thumbnail_picture = cv2.cvtColor(self.thumbnail_picture, cv2.COLOR_BGR2RGB)
        self.thumbnail_picture = cv2.resize(self.thumbnail_picture, (thumbnail_label_width, thumbnail_label_height))
        q_image = QImage(self.thumbnail_picture[:], thumbnail_label_width, thumbnail_label_height, thumbnail_label_width * 3,
                         QImage.Format_RGB888)
        self.thumbnail_label.setPixmap(QPixmap(q_image))
        self.load_change()

    def show_video(self):
        global buffer
        self.video_panel.setPixmap(QPixmap(buffer))

    def save_image(self):
        global hide_mark_state
        if hide_mark_state == 1:
            self.hide_mark()
        global all_point
        global all_mark_text
        global all_start_list
        self.save_change()
        save_data = []
        save_data.append(all_point)
        save_data.append(all_mark_text)
        save_data.append(all_start_list)
        output_path = self.img_path.split(".")[0] + ".pkl"
        output = open(output_path, 'wb')
        pickle.dump(save_data, output)


    def save_change(self):
        self.pixel_map.save(self.img_path)
        global tmp_point
        if len(tmp_point):
            for i in range(0, len(tmp_point)):
                if (i+1) != len(tmp_point):
                    if tmp_point[i][0] == -1 or tmp_point[i+1][0] == -1:
                        continue
                    else:
                        cv2.line(self.picture, (tmp_point[i][0]+all_start, tmp_point[i][1]), (tmp_point[i+1][0]+all_start, tmp_point[i+1][1]), (0, 0, 255), 4)


        global tmp_mark_text
        if len(tmp_mark_text):
            for l in range(0, len(tmp_mark_text)):
                font = cv2.FONT_HERSHEY_COMPLEX
                cv2.putText(self.picture, tmp_mark_text[l][2], (tmp_mark_text[l][0]+all_start, tmp_mark_text[l][1]), font, 1, (0, 255, 255), 2)


        self.thumbnail_picture = self.picture.copy()
        self.thumbnail_picture = cv2.cvtColor(self.thumbnail_picture, cv2.COLOR_BGR2RGB)
        self.thumbnail_picture = cv2.resize(self.thumbnail_picture, (thumbnail_label_width, thumbnail_label_height))
        q_image = QImage(self.thumbnail_picture[:], thumbnail_label_width, thumbnail_label_height, thumbnail_label_width * 3,
                         QImage.Format_RGB888)
        self.thumbnail_label.setPixmap(QPixmap(q_image))
        global all_point
        global all_mark_text
        if len(tmp_point) != 0:
            all_point.append(copy.deepcopy(tmp_point))
            all_start_list.append(all_start)
            print(all_point)
            print(all_start_list)
        if len(tmp_mark_text) != 0:
            all_mark_text.append(copy.deepcopy(tmp_mark_text))
        tmp_point.clear()
        tmp_mark_text.clear()

    def load_change(self):
        global all_point
        global all_start_list
        global all_start
        for k in range(len(all_point)):
            point = all_point[k]
            all_start = all_start_list[k]
            if len(point):
                for i in range(0, len(point)):
                    if (i + 1) != len(point):
                        if point[i][0] == -1 or point[i + 1][0] == -1:
                            continue
                        else:
                            cv2.line(self.picture, (point[i][0] + all_start, point[i][1]),
                                     (point[i + 1][0] + all_start, point[i + 1][1]), (0, 0, 255), 4)


        global all_mark_text
        for k in range(len(all_mark_text)):
            mark_text = all_mark_text[k]
            all_start = all_start_list[k]
            if len(mark_text):
                for l in range(0, len(mark_text)):
                    font = cv2.FONT_HERSHEY_COMPLEX
                    cv2.putText(self.picture, mark_text[l][2],
                                (mark_text[l][0] + all_start, mark_text[l][1]), font, 1, (0, 255, 255), 2)

            self.thumbnail_picture = self.picture.copy()
            self.thumbnail_picture = cv2.cvtColor(self.thumbnail_picture, cv2.COLOR_BGR2RGB)
            self.thumbnail_picture = cv2.resize(self.thumbnail_picture, (thumbnail_label_width, thumbnail_label_height))
            q_image = QImage(self.thumbnail_picture[:], thumbnail_label_width, thumbnail_label_height, thumbnail_label_width * 3,
                             QImage.Format_RGB888)
            self.thumbnail_label.setPixmap(QPixmap(q_image))
        self.image_panel.update()



    def save_as_image(self):
        global hide_mark_state
        if hide_mark_state == 1:
            self.hide_mark()
        global all_point
        global all_mark_text
        self.save_change()
        save_data = []
        save_data.append(all_point)
        save_data.append(all_mark_text)
        save_as_image_name = QFileDialog.getSaveFileName(self, 'Save AS File', '/', 'jpg(*.jpg)')
        output_path = save_as_image_name[0].split(".")[0] + ".pkl"
        output = open(output_path, 'wb')
        pickle.dump(all_point, output)

    def close_image(self):
        self.image_panel.clear()
        global point
        point = []
        global mark_text
        mark_text = []

    def draw_mark(self):
        global tmp_point
        mark_x = tmp_point[len(tmp_point)-1][0]
        mark_y = tmp_point[len(tmp_point)-1][1]
        global tmp_mark_text
        tmp_mark_text.append([mark_x, mark_y, self.input_mark.text()])
        tmp_point.append([-1, -1])
        self.image_panel.update()

    def thumnail_clicked(self):
        self.save_change()
        self.show_thumbnail_picture()

    def show_thumbnail_picture(self):
        global thumbnail_x
        x = self.thumbnail_to_orignal(thumbnail_x)
        img = self.picture.copy()
        start = int(max(x-rect_width/2, 0))
        end = int(min(x+rect_width/2, img.shape[1]))
        if start == 0:
            end = rect_width + 1
        if end == img.shape[1]:
            start = img.shape[1] - rect_width - 1

        global all_start
        all_start = start
        global all_end
        all_end = end

        img = cv2.cvtColor(self.picture, cv2.COLOR_BGR2RGB)[:, start:end].copy()
        print("11111")
        q_image = QImage(img[:], img.shape[1], img.shape[0], img.shape[1] * 3,
                         QImage.Format_RGB888)
        q_pixmap = QPixmap(q_image)
        self.image_panel.resize(q_pixmap.width(), q_pixmap.height())
        self.image_panel.setPixmap(q_pixmap)
        self.image_panel.setAlignment(Qt.AlignCenter)
        self.draw_rect()

    def thumbnail_to_orignal(self, x):
        x = int(x / thumbnail_label_width * original_img_width)
        return x

    def draw_rect(self):
        semi_w = int(rect_width/ 2 /original_img_width * thumbnail_label_width )
        global thumbnail_x
        x = thumbnail_x
        start = max(x - semi_w, 0)
        end = min(x + semi_w, thumbnail_label_width)
        if start == 0:
            end = 2 * semi_w + 1
        if end == thumbnail_label_width:
            start = thumbnail_label_width - semi_w*2 - 1
        img = self.thumbnail_picture.copy()
        img = cv2.rectangle(img, (start, 0), (end, thumbnail_label_height), (0, 255, 0), 2)
        q_image = QImage(img[:], thumbnail_label_width, thumbnail_label_height, thumbnail_label_width * 3,
                         QImage.Format_RGB888)
        self.thumbnail_label.setPixmap(QPixmap(q_image))

    def hide_mark(self):
        global hide_mark_state
        global all_point
        global all_mark_text
        global tmp_all_point
        global tmp_all_mark_text
        global tmp_point
        global tmp_mark_text
        global tmp_tmp_point
        global tmp_tmp_mark_text
        if hide_mark_state == 0:
            tmp_tmp_point = copy.deepcopy(tmp_point)
            tmp_tmp_mark_text = copy.deepcopy(tmp_mark_text)
            tmp_all_point = copy.deepcopy(all_point)
            tmp_all_mark_text = copy.deepcopy(all_mark_text)
            tmp_point.clear()
            tmp_mark_text.clear()
            all_point.clear()
            all_mark_text.clear()
            self.picture = self.original_picture.copy()
            hide_mark_state = 1
            self.load_image(self.img_path)
            self.show_thumbnail_picture()
        else:
            tmp_point = copy.deepcopy(tmp_tmp_point)
            tmp_mark_text = copy.deepcopy(tmp_tmp_mark_text)
            all_point = copy.deepcopy(tmp_all_point)
            all_mark_text = copy.deepcopy(tmp_all_mark_text)
            hide_mark_state = 0
            self.load_image(self.img_path)
            self.show_thumbnail_picture()
        self.image_panel.update()

    def show_window(self):
        pkl_file_path = self.img_path.split(".")[0] + ".pkl"
        self.open_image(self.img_path, pkl_file_path)
        self.mythread.start()
        self.show()

    def up_pressed(self):
        up_rotate_start(id, dll)

    def up_released(self):
        up_rotate_stop(id, dll)

    def down_pressed(self):
        down_rotate_start(id, dll)

    def down_released(self):
        down_rotate_stop(id, dll)

    def left_pressed(self):
        left_rotate_start(id, dll)

    def left_released(self):
        left_rotate_stop(id, dll)

    def right_pressed(self):
        right_rotate_start(id, dll)

    def right_released(self):
        right_rotate_stop(id, dll)

    def focus_near_pressed(self):
        focus_near_start(id, dll)

    def focus_near_released(self):
        focus_near_stop(id, dll)

    def focus_far_pressed(self):
        focus_far_start(id, dll)

    def focus_far_released(self):
        focus_far_stop(id, dll)

    def zoom_in_pressed(self):
        zoom_in_start(id, dll)

    def zoom_in_released(self):
        zoom_in_stop(id, dll)

    def zoom_out_pressed(self):
        zoom_out_start(id, dll)

    def zoom_out_released(self):
        zoom_out_stop(id, dll)


#if __name__ == '__main__':
#     app = QApplication(sys.argv)
#     app.setApplicationName("Image Mask")
#     window = MarkWindow()
#     sys.exit(app.exec_())
Exemplo n.º 41
0
    def __init__(self, parent=None):
        super(VideoWindow, self).__init__(parent)
        self.setWindowTitle("ONI Player")
        self.setWindowIcon(QIcon('images/play.png'))
        self.vsource = None

        class MediaPlayer(QMediaPlayer):
            def __init__(self, parent=None, flags=QMediaPlayer.VideoSurface):
                super(MediaPlayer, self).__init__(parent)
                self.parent = parent

            def frame_step(self, direction):
                frames = list(map(round, self.parent.vsource.track.timecodes))
                if 0 < self.position() < max(frames):
                    dif = [abs(self.position() - x) for x in frames]
                    self.setPosition(frames[dif.index(min(dif)) + direction])

        self.colorMediaPlayer = MediaPlayer(parent=self)
        self.depthMediaPlayer = MediaPlayer(parent=self)

        self.colorVideoWidget = QVideoWidget()
        self.depthVideoWidget = QVideoWidget()

        # spacers for control panel
        self.leftSpacerItem = QSpacerItem(10, 10, QSizePolicy.Expanding,
                                          QSizePolicy.Minimum)
        self.rightSpacerItem = QSpacerItem(10, 10, QSizePolicy.Expanding,
                                           QSizePolicy.Minimum)

        # buttom for control panel
        self.backButton = QPushButton()
        self.backButton.setEnabled(False)
        self.backButton.setIcon(self.style().standardIcon(
            QStyle.SP_MediaSeekBackward))
        self.backButton.clicked.connect(lambda: self.prev_next_frame(-1))
        self.backButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Minimum)

        self.playButton = QPushButton()
        self.playButton.setEnabled(False)
        self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.playButton.clicked.connect(self.play)
        self.playButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Minimum)

        self.forwardButton = QPushButton()
        self.forwardButton.setEnabled(False)
        self.forwardButton.setIcon(self.style().standardIcon(
            QStyle.SP_MediaSeekForward))
        self.forwardButton.clicked.connect(lambda: self.prev_next_frame(1))
        self.forwardButton.setSizePolicy(QSizePolicy.Fixed,
                                         QSizePolicy.Minimum)

        self.positionSlider = QSlider(Qt.Horizontal)
        self.positionSlider.setRange(0, 0)
        self.positionSlider.sliderMoved.connect(self.setPosition)

        self.errorLabel = QLabel()
        self.errorLabel.setSizePolicy(QSizePolicy.Preferred,
                                      QSizePolicy.Maximum)
        self.colorLabel = QLabel('Color stream')
        self.depthLabel = QLabel('Depth stream')
        self.hframe = QFrame(self)
        self.hframe.setFrameShape(QFrame.HLine)
        self.hframe.setFrameShadow(QFrame.Raised)
        # self.hframe.setLineWidth(1)

        # Create new action
        openAction = QAction(QIcon('open.png'), '&Open', self)
        openAction.setShortcut('Ctrl+O')
        openAction.setStatusTip('Open movie')
        openAction.triggered.connect(self.openFile)

        # Create exit action
        exitAction = QAction(QIcon('exit.png'), '&Exit', self)  # png!!!
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(self.exitCall)

        # Create menu bar and add action
        menuBar = self.menuBar()
        fileMenu = menuBar.addMenu('&File')
        fileMenu.addAction(openAction)
        fileMenu.addAction(exitAction)

        # Create a widget for window contents
        wid = QWidget(self)
        self.setCentralWidget(wid)

        # Create layouts to place inside widget
        controlLayout = QHBoxLayout()
        controlLayout.addSpacerItem(self.leftSpacerItem)
        controlLayout.addWidget(self.backButton)
        controlLayout.addWidget(self.playButton)
        controlLayout.addWidget(self.forwardButton)
        controlLayout.addSpacerItem(self.rightSpacerItem)

        self.videoLayout = QGridLayout()
        self.videoLayout.setSpacing(10)
        self.videoLayout.addWidget(self.colorLabel, 0, 0, Qt.AlignCenter)
        self.videoLayout.addWidget(self.depthLabel, 0, 1, Qt.AlignCenter)
        self.videoLayout.addWidget(self.colorVideoWidget, 1, 0)
        self.videoLayout.addWidget(self.depthVideoWidget, 1, 1)

        layout = QVBoxLayout()
        layout.addLayout(self.videoLayout)
        layout.addWidget(self.positionSlider)
        layout.addLayout(controlLayout)
        layout.addWidget(self.hframe)
        layout.addWidget(self.errorLabel)

        # Set widget to contain window contents
        wid.setLayout(layout)

        self.colorMediaPlayer.setVideoOutput(self.colorVideoWidget)
        self.colorMediaPlayer.stateChanged.connect(self.mediaStateChanged)
        self.colorMediaPlayer.positionChanged.connect(self.positionChanged)
        self.colorMediaPlayer.durationChanged.connect(self.durationChanged)
        self.colorMediaPlayer.error.connect(self.handleError)

        self.depthMediaPlayer.setVideoOutput(self.depthVideoWidget)
        self.depthMediaPlayer.stateChanged.connect(self.mediaStateChanged)
        self.depthMediaPlayer.positionChanged.connect(self.positionChanged)
        self.depthMediaPlayer.durationChanged.connect(self.durationChanged)
        self.depthMediaPlayer.error.connect(self.handleError)
Exemplo n.º 42
0
 def leaveEvent(self, event):
     self.font.setUnderline(False)
     self.setFont(self.font)
     self.app.setOverrideCursor(QCursor(Qt.ArrowCursor))
     return QLabel.leaveEvent(self, event)
Exemplo n.º 43
0
    def __init__(self):
        super().__init__()

        # set exit button
        self.exit_button = QPushButton(self)
        self.exit_button.setIcon(QIcon("./icon/quit.png"))
        self.exit_button.setShortcut('Ctrl+Q')
        self.exit_button.setFixedHeight(32)
        self.exit_button.setFixedWidth(32)
        self.exit_button.setToolTip("Quit APP")
        self.exit_button.clicked.connect(qApp.quit)


        # set open button
        self.open_button = QPushButton(self)
        self.open_button.setIcon(QIcon("./icon/open.png"))
        self.open_button.setShortcut('Ctrl+O')
        self.open_button.setFixedHeight(32)
        self.open_button.setFixedWidth(32)
        self.open_button.setToolTip("Open Image")
        self.open_button.clicked.connect(self.open_image)
        self.image_name = ''

        # set save button
        self.save_button = QPushButton(self)
        self.save_button.setIcon(QIcon("./icon/save.png"))
        self.save_button.setShortcut('Ctrl+S')
        self.save_button.setFixedHeight(32)
        self.save_button.setFixedWidth(32)
        self.save_button.setToolTip("Save Image")
        self.save_button.clicked.connect(self.save_image)


        # set save_as button
        self.save_as_button = QPushButton(self)
        self.save_as_button.setIcon(QIcon("./icon/save_as.png"))
        self.save_as_button.setShortcut('Ctrl+S')
        self.save_as_button.setFixedHeight(32)
        self.save_as_button.setFixedWidth(32)
        self.save_as_button.setToolTip("Save As Image")
        self.save_as_button.clicked.connect(self.save_as_image)

        # set close button
        self.close_button = QPushButton(self)
        self.close_button.setIcon(QIcon("./icon/close.png"))
        self.close_button.setShortcut('Ctrl+E')
        self.close_button.setFixedHeight(32)
        self.close_button.setFixedWidth(32)
        self.close_button.setToolTip("Close Image")
        self.close_button.clicked.connect(self.close_image)

        # set draw rectangle button
        self.label_button = QPushButton(self)
        self.label_button.setIcon(QIcon("./icon/mark.png"))
        self.label_button.setShortcut('Ctrl+R')
        self.label_button.setFixedHeight(32)
        self.label_button.setFixedWidth(32)
        self.label_button.setToolTip("Draw Label")
        self.label_button.clicked.connect(self.draw_mark)

        # set hide mark button
        self.hide_mark_button = QPushButton(self)
        self.hide_mark_button.setIcon(QIcon("./icon/hide.png"))
        self.hide_mark_button.setShortcut('Ctrl+R')
        self.hide_mark_button.setFixedHeight(32)
        self.hide_mark_button.setFixedWidth(32)
        self.hide_mark_button.setToolTip("Hide Label")
        self.hide_mark_button.clicked.connect(self.hide_mark)

        # set up button
        self.up_button = QPushButton(self)
        self.up_button.setIcon(QIcon("./icon/up.png"))
        self.up_button.setShortcut('Ctrl+U')
        self.up_button.setFixedHeight(control_button_height)
        self.up_button.setFixedWidth(control_button_width)
        self.up_button.setToolTip("Up Camera")
        self.up_button.pressed.connect(self.up_pressed)
        self.up_button.released.connect(self.up_released)

        # set down button
        self.down_button = QPushButton(self)
        self.down_button.setIcon(QIcon("./icon/down.png"))
        self.down_button.setShortcut('Ctrl+D')
        self.down_button.setFixedHeight(control_button_height)
        self.down_button.setFixedWidth(control_button_width)
        self.down_button.setToolTip("Down Camera")
        self.down_button.pressed.connect(self.down_pressed)
        self.down_button.released.connect(self.down_released)
        self.image_name = ''

        # set left button
        self.left_button = QPushButton(self)
        self.left_button.setIcon(QIcon("./icon/left.png"))
        self.left_button.setShortcut('Ctrl+L')
        self.left_button.setFixedHeight(control_button_height)
        self.left_button.setFixedWidth(control_button_width)
        self.left_button.setToolTip("Ledt Camera")
        self.left_button.pressed.connect(self.left_pressed)
        self.left_button.released.connect(self.left_released)

        # set right button
        self.right_button = QPushButton(self)
        self.right_button.setIcon(QIcon("./icon/right.png"))
        self.right_button.setShortcut('Ctrl+R')
        self.right_button.setFixedHeight(control_button_height)
        self.right_button.setFixedWidth(control_button_width)
        self.right_button.setToolTip("Right Camera")
        self.right_button.pressed.connect(self.right_pressed)
        self.right_button.released.connect(self.right_released)

        # set focus near button
        self.focus_near_button = QPushButton(self)
        self.focus_near_button.setIcon(QIcon("./icon/focus_near.png"))
        self.focus_near_button.setShortcut('Ctrl+N')
        self.focus_near_button.setFixedHeight(control_button_height)
        self.focus_near_button.setFixedWidth(control_button_width)
        self.focus_near_button.setToolTip("Focus Near Image")
        self.focus_near_button.pressed.connect(self.focus_near_pressed)
        self.focus_near_button.released.connect(self.focus_near_released)

        # set focus far button
        self.focus_far_button = QPushButton(self)
        self.focus_far_button.setIcon(QIcon("./icon/focus_far.png"))
        self.focus_far_button.setShortcut('Ctrl+F')
        self.focus_far_button.setFixedHeight(control_button_height)
        self.focus_far_button.setFixedWidth(control_button_width)
        self.focus_far_button.setToolTip("Focus Far Image")
        self.focus_far_button.pressed.connect(self.focus_far_pressed)
        self.focus_far_button.released.connect(self.focus_far_released)

        # set zoom in button
        self.zoom_in_button = QPushButton(self)
        self.zoom_in_button.setIcon(QIcon("./icon/zoom_in.png"))
        self.zoom_in_button.setShortcut('Ctrl+Z+I')
        self.zoom_in_button.setFixedHeight(control_button_height)
        self.zoom_in_button.setFixedWidth(control_button_width)
        self.zoom_in_button.setToolTip("Zoom In Image")
        self.zoom_in_button.pressed.connect(self.zoom_in_pressed)
        self.zoom_in_button.released.connect(self.zoom_in_released)

        # set zoom out button
        self.zoom_out_button = QPushButton(self)
        self.zoom_out_button.setIcon(QIcon("./icon/zoom_out.png"))
        self.zoom_out_button.setShortcut('Ctrl+Z+O')
        self.zoom_out_button.setFixedHeight(control_button_height)
        self.zoom_out_button.setFixedWidth(control_button_width)
        self.zoom_out_button.setToolTip("Zoom Out Image")
        self.zoom_out_button.pressed.connect(self.zoom_out_pressed)
        self.zoom_out_button.released.connect(self.zoom_out_released)

        #thumbnail QLabel
        self.thumbnail_label = myLabel()
        self.thumbnail_label.clicked.connect(self.thumnail_clicked)

        self.video_panel = QLabel()
        self.video_panel.setFixedWidth(400)
        self.video_panel.setFixedHeight(400)
        self.video_panel.setScaledContents(True)
        # set zoom ratio
        self.zoom_ratio = 1

        self.h_layout_tool_bar = QHBoxLayout()
        self.h_layout_tool_bar.addWidget(self.exit_button)
        self.h_layout_tool_bar.addWidget(self.open_button)
        self.h_layout_tool_bar.addWidget(self.save_button)
        self.h_layout_tool_bar.addWidget(self.save_as_button)
        self.h_layout_tool_bar.addWidget(self.close_button)
        self.h_layout_tool_bar.addWidget(self.label_button)
        self.h_layout_tool_bar.addWidget(self.hide_mark_button)
        self.tool_bar = QWidget()
        self.tool_bar.setLayout(self.h_layout_tool_bar)
        self.tool_bar.setFixedHeight(50)

        self.h_layout_thumbnail = QHBoxLayout()
        self.h_layout_thumbnail.addWidget(self.thumbnail_label)
        self.thumbnail = QWidget()
        self.thumbnail.setLayout(self.h_layout_thumbnail)
        # global thumbnail_label_height
        # global thumbnail_label_width
        # self.thumbnail.setFixedHeight(thumbnail_label_height)
        # self.thumbnail.setFixedWidth(thumbnail_label_width)

        self.picture = ''
        self.original_picture = ''
        self.thumbnail_picture=''
        self.pixel_map = QPixmap()
        self.image_panel = ImageLabel()
        self.image_panel.setScaledContents(True)

        self.scroll_area = QScrollArea()
        self.scroll_area.setWidget(self.image_panel)
        self.scroll_area.setAlignment(Qt.AlignCenter)

        self.input_mark = QLineEdit()
        self.input_mark.setFixedHeight(30)
        self.input_mark.setAlignment(Qt.AlignCenter)

        self.h_layout_left_area = QVBoxLayout()
        self.h_layout_left_area.addWidget(self.tool_bar)
        self.h_layout_left_area.addWidget(self.scroll_area)
        self.h_layout_left_area.addWidget(self.input_mark)
        self.left_area = QWidget()
        self.left_area.setLayout(self.h_layout_left_area)

        self.h_layout_control_1 = QHBoxLayout()
        self.h_layout_control_1.addWidget(self.up_button)
        self.h_layout_control_1.addWidget(self.down_button)
        self.h_layout_control_1.addWidget(self.focus_near_button)
        self.h_layout_control_1.addWidget(self.focus_far_button)
        self.control_1 = QWidget()
        self.control_1.setLayout(self.h_layout_control_1)

        self.h_layout_control_2 = QHBoxLayout()
        self.h_layout_control_2.addWidget(self.left_button)
        self.h_layout_control_2.addWidget(self.right_button)
        self.h_layout_control_2.addWidget(self.zoom_in_button)
        self.h_layout_control_2.addWidget(self.zoom_out_button)
        self.control_2 = QWidget()
        self.control_2.setLayout(self.h_layout_control_2)

        self.h_layout_control_pannel = QVBoxLayout()
        self.h_layout_control_pannel.addWidget(self.control_1)
        self.h_layout_control_pannel.addWidget(self.control_2)
        self.h_layout_control_pannel.setAlignment(Qt.AlignCenter)
        self.control_pannel = QWidget()
        self.control_pannel.setLayout(self.h_layout_control_pannel)

        self.h_layout_video_frame = QHBoxLayout()
        self.h_layout_video_frame.addWidget(self.video_panel)
        self.h_layout_video_frame.setAlignment(Qt.AlignCenter)
        self.video_frame = QWidget()
        self.video_frame.setLayout(self.h_layout_video_frame)

        self.h_layout_right_area = QVBoxLayout()
        self.h_layout_right_area.addWidget(self.video_frame)
        self.h_layout_right_area.addWidget(self.control_pannel)
        self.right_area = QWidget()
        self.right_area.setLayout(self.h_layout_right_area)

        self.h_layout = QHBoxLayout()
        self.h_layout.addWidget(self.left_area)
        self.h_layout.addWidget(self.right_area)
        self.top_area = QWidget()
        self.top_area.setLayout(self.h_layout)

        self.v_layout = QVBoxLayout()
        self.v_layout.addWidget(self.top_area)
        self.v_layout.addWidget(self.thumbnail)
        self.setLayout(self.v_layout)

        self.setMouseTracking(False)
        self.setWindowIcon(QIcon('./icons/icon.png'))
        self.img_path = "result.jpg"

        self.mythread = VideoThread()
        self.mythread.signal.connect(self.show_video)
Exemplo n.º 44
0
 def __init__(self, text, help_text):
     QLabel.__init__(self, text)
     self.help_text = help_text
     self.app = QCoreApplication.instance()
     self.font = QFont()
Exemplo n.º 45
0
 def __init__(self, text="", parent=None):
     QLabel.__init__(self, text, parent)
     self.setWordWrap(True)
     self.setTextInteractionFlags(Qt.TextSelectableByMouse)
    def on_btnSave_clicked(self):
        simulationType_txt = self.simulationType.currentText()
        RASModel_txt = self.RASModel.currentText()
        turbulence_txt = self.turbulence.currentText()
        printCoeffs_txt = self.printCoeffs.currentText()
        
        if 'turbulenceProperties' not in self.con.tables():
            query = QtSql.QSqlQuery()
            query.exec("CREATE TABLE turbulenceProperties(param, value)")

            query.exec("INSERT INTO turbulenceProperties(param, value) VALUES ('%s','%s')" % ('simulationType', ''))
            query.exec("INSERT INTO turbulenceProperties(param, value) VALUES ('%s','%s')" % ('RASModel', ''))
            query.exec("INSERT INTO turbulenceProperties(param, value) VALUES ('%s','%s')" % ('turbulence', ''))
            query.exec("INSERT INTO turbulenceProperties(param, value) VALUES ('%s','%s')" % ('printCoeffs', ''))

        if 'turbulenceProperties' in self.con.tables():
            query = QtSql.QSqlQuery()

            query.prepare("UPDATE turbulenceProperties SET value=? WHERE param='simulationType'")
            query.bindValue(0, simulationType_txt)
            query.exec_()

            query.prepare("UPDATE turbulenceProperties SET value=? WHERE param='RASModel'")
            query.bindValue(0, RASModel_txt)
            query.exec_()

            query.prepare("UPDATE turbulenceProperties SET value=? WHERE param='turbulence'")
            query.bindValue(0, turbulence_txt)
            query.exec_()

            query.prepare("UPDATE turbulenceProperties SET value=? WHERE param='printCoeffs'")
            query.bindValue(0, printCoeffs_txt)
            query.exec_()

        # записываем файл turbulenceProperties
        if os.path.exists(self.full_dir + '/constant/turbulenceProperties'):
            os.remove(self.full_dir + '/constant/turbulenceProperties')
		
        shutil.copyfile("./matches/Shablon/constant/turbulenceProperties", self.full_dir + '/constant/turbulenceProperties')
		
        tP = open(self.full_dir + '/constant/turbulenceProperties', 'a')
		
        ###simulationType###
        sT_bl = '\n' + 'simulationType     ' + simulationType_txt + ';' + '\n'

        RAS_start_bl = '\n' + 'RAS' + '\n' + '{'

        ###RASModel###
        RASModel_bl = '\n' + '    ' + 'RASModel        ' + RASModel_txt + ';' + '\n\n'

        ###turbulence###
        turbulence_bl = '\n' + '    ' + 'turbulence      ' + turbulence_txt + ';' + '\n\n'

        ###printCoeffs###
        printCoeffs_bl = '\n' + '    ' + 'printCoeffs     ' + printCoeffs_txt + ';' + '\n'

        RAS_end_bl = '}' + '\n\n'

        tP.write(sT_bl + RAS_start_bl + RASModel_bl + turbulence_bl + printCoeffs_bl + RAS_end_bl)
        close_str = '// ************************************************************************* //'
        tP.write(close_str)

        tP.close()

        self.par.cdw.setWidget(self.par.outf_scroll)
        outf = open(self.full_dir + '/constant/turbulenceProperties')

        if self.interface_lng_val == 'Russian':
            msg_lbl = QLabel(
                '<span style="color:green">Файл turbulenceProperties сохранен</span>')
        elif self.interface_lng_val == 'English':
            msg_lbl = QLabel(
                '<span style="color:green">The turbulenceProperties file saved</span>')

        self.par.listWidget.clear()
        self.par.item = QListWidgetItem()
        self.par.listWidget.addItem(self.par.item)
        self.par.listWidget.setItemWidget(self.par.item, msg_lbl)

        data = outf.read()

        if self.interface_lng_val == 'Russian':
            self.par.outf_lbl.setText("Файл " + "<font color='peru'>" + 'turbulenceProperties' + "</font>")
        elif self.interface_lng_val == 'English':
            self.par.outf_lbl.setText("<font color='peru'>" + 'turbulenceProperties' + "</font>" + " file")
        self.par.outf_edit.setText(data)

        self.par.cdw.setTitleBarWidget(self.par.cdw_frame)
        outf.close()
Exemplo n.º 47
0
 def enterEvent(self, event):
     self.font.setUnderline(True)
     self.setFont(self.font)
     self.app.setOverrideCursor(QCursor(Qt.PointingHandCursor))
     return QLabel.enterEvent(self, event)
Exemplo n.º 48
0
    def request_safe_t_init_settings(self, wizard, method, device):
        vbox = QVBoxLayout()
        next_enabled = True
        label = QLabel(_("Enter a label to name your device:"))
        name = QLineEdit()
        hl = QHBoxLayout()
        hl.addWidget(label)
        hl.addWidget(name)
        hl.addStretch(1)
        vbox.addLayout(hl)

        def clean_text(widget):
            text = widget.toPlainText().strip()
            return ' '.join(text.split())

        if method in [TIM_NEW, TIM_RECOVER]:
            gb = QGroupBox()
            hbox1 = QHBoxLayout()
            gb.setLayout(hbox1)
            vbox.addWidget(gb)
            gb.setTitle(_("Select your seed length:"))
            bg = QButtonGroup()
            for i, count in enumerate([12, 18, 24]):
                rb = QRadioButton(gb)
                rb.setText(_("{:d} words").format(count))
                bg.addButton(rb)
                bg.setId(rb, i)
                hbox1.addWidget(rb)
                rb.setChecked(True)
            cb_pin = QCheckBox(_('Enable PIN protection'))
            cb_pin.setChecked(True)
        else:
            text = QTextEdit()
            text.setMaximumHeight(60)
            if method == TIM_MNEMONIC:
                msg = _("Enter your BIP39 mnemonic:")
            else:
                msg = _("Enter the master private key beginning with xprv:")

                def set_enabled():
                    from electrum_xzc.bip32 import is_xprv
                    wizard.next_button.setEnabled(is_xprv(clean_text(text)))

                text.textChanged.connect(set_enabled)
                next_enabled = False

            vbox.addWidget(QLabel(msg))
            vbox.addWidget(text)
            pin = QLineEdit()
            pin.setValidator(QRegExpValidator(QRegExp('[1-9]{0,9}')))
            pin.setMaximumWidth(100)
            hbox_pin = QHBoxLayout()
            hbox_pin.addWidget(QLabel(_("Enter your PIN (digits 1-9):")))
            hbox_pin.addWidget(pin)
            hbox_pin.addStretch(1)

        if method in [TIM_NEW, TIM_RECOVER]:
            vbox.addWidget(WWLabel(RECOMMEND_PIN))
            vbox.addWidget(cb_pin)
        else:
            vbox.addLayout(hbox_pin)

        passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT)
        passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
        passphrase_warning.setStyleSheet("color: red")
        cb_phrase = QCheckBox(_('Enable passphrases'))
        cb_phrase.setChecked(False)
        vbox.addWidget(passphrase_msg)
        vbox.addWidget(passphrase_warning)
        vbox.addWidget(cb_phrase)

        wizard.exec_layout(vbox, next_enabled=next_enabled)

        if method in [TIM_NEW, TIM_RECOVER]:
            item = bg.checkedId()
            pin = cb_pin.isChecked()
        else:
            item = ' '.join(str(clean_text(text)).split())
            pin = str(pin.text())

        return (item, name.text(), pin, cb_phrase.isChecked())
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.interface_lng_val = parent.interface_lng_val
        self.con = parent.con
        self.full_dir = parent.full_dir
        self.par = parent

        if self.con.open():

            self.table = QTableWidget(4, 2)
            self.table.setColumnWidth(0, 150)
            self.table.setColumnWidth(1, 230)
            self.table.setFixedSize(674, 480)
            if self.interface_lng_val == 'Russian':
                self.table.setHorizontalHeaderLabels(["Параметр", "Значение"])
            elif self.interface_lng_val == 'English':
                self.table.setHorizontalHeaderLabels(["Parameter", "Value"])
            # simulationType
            simulationType_lbl = QLabel('simulationType')
            self.simulationType = QComboBox()
            simulationType_list = ["laminar", "RAS"]
            self.simulationType.addItems(simulationType_list)

            #RASModel
            RASModel_lbl = QLabel('RASModel')
            self.RASModel = QComboBox()
            RASModel_list = ["kkLOmega", "demo"]
            self.RASModel.addItems(RASModel_list)

            #turbulence
            turbulence_lbl = QLabel('turbulence')
            self.turbulence = QComboBox()
            turbulence_list = ["on", "off"]
            self.turbulence.addItems(turbulence_list)

            #printCoeffs
            printCoeffs_lbl = QLabel('printCoeffs')
            self.printCoeffs = QComboBox()
            printCoeffs_list = ["on", "off"]
            self.printCoeffs.addItems(printCoeffs_list)






            self.table.setCellWidget(0, 1, self.simulationType)
            self.table.setCellWidget(0, 0, simulationType_lbl)

            self.table.setCellWidget(1, 1, self.RASModel)
            self.table.setCellWidget(1, 0, RASModel_lbl)

            self.table.setCellWidget(2, 1, self.turbulence)
            self.table.setCellWidget(2, 0, turbulence_lbl)

            self.table.setCellWidget(3, 1, self.printCoeffs)
            self.table.setCellWidget(3, 0, printCoeffs_lbl)

            # вывод значений параметров
            if 'turbulenceProperties' in self.con.tables():						
                query = QtSql.QSqlQuery()
                query.exec("SELECT * FROM turbulenceProperties")
                if query.isActive():
                    query.first()
                    value_list = []
                    while query.isValid():
                        value_res = query.value('value')
                        value_list.append(value_res)
                        query.next()
					
                    # simulationType
                    simulationType_mas = self.simulationType.count()   
                    for i in range(simulationType_mas):
                        if self.simulationType.itemText(i) == value_list[0]:
                            self.simulationType.setCurrentIndex(i)

                    # RASModel
                    RASModel_mas = self.RASModel.count()
                    for i in range(RASModel_mas):
                        if self.RASModel.itemText(i) == value_list[1]:
                            self.RASModel.setCurrentIndex(i)

                    # turbulence
                    turbulence_mas = self.turbulence.count()
                    for i in range(turbulence_mas):
                        if self.turbulence.itemText(i) == value_list[2]:
                            self.turbulence.setCurrentIndex(i)

                    # printCoeffs
                    printCoeffs_mas = self.printCoeffs.count()
                    for i in range(printCoeffs_mas):
                        if self.printCoeffs.itemText(i) == value_list[3]:
                            self.printCoeffs.setCurrentIndex(i)
							
            btnSave = QPushButton()
            btnSave.setFixedSize(80, 25)
            btnSave.clicked.connect(self.on_btnSave_clicked)

            if self.interface_lng_val == 'Russian':
                btnSave.setText("Сохранить")
            elif self.interface_lng_val == 'English':
                btnSave.setText("Save")

            vbox = QVBoxLayout()
            vbox.addWidget(self.table)
            vbox.addWidget(btnSave)

# ---------------------Размещение на форме всех компонентов-------------------------

            form = QFormLayout()
            form.addRow(vbox)
            self.setLayout(form)
Exemplo n.º 50
0
class QtCrackWidget(QWidget):

    closeCrackWidget = pyqtSignal()

    def __init__(self, map, blob, x, y, parent=None):
        super(QtCrackWidget, self).__init__(parent)

        self.setStyleSheet("background-color: rgb(60,60,65); color: white")

        self.qimg_cropped = utils.cropQImage(map, blob.bbox)
        arr = utils.qimageToNumpyArray(self.qimg_cropped)
        self.input_arr = rgb2gray(arr) * 255
        self.tolerance = 20
        self.blob = blob
        self.xmap = x
        self.ymap = y
        self.qimg_crack = QImage(self.qimg_cropped.width(), self.qimg_cropped.height(), QImage.Format_RGB32)
        self.qimg_crack.fill(qRgb(0, 0, 0))

        self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.setFixedWidth(400)
        self.setFixedHeight(400)

        SLIDER_WIDTH = 200
        IMAGEVIEWER_SIZE = 300  # SIZE x SIZE

        self.sliderTolerance = QSlider(Qt.Horizontal)
        self.sliderTolerance.setFocusPolicy(Qt.StrongFocus)
        self.sliderTolerance.setMinimumWidth(SLIDER_WIDTH)
        self.sliderTolerance.setMinimum(1)
        self.sliderTolerance.setMaximum(100)
        self.sliderTolerance.setValue(self.tolerance)
        self.sliderTolerance.setTickInterval(5)
        self.sliderTolerance.setAutoFillBackground(True)
        self.sliderTolerance.valueChanged.connect(self.sliderToleranceChanged)

        self.lblTolerance = QLabel("Tolerance: 20")
        self.lblTolerance.setAutoFillBackground(True)
        str = "Tolerance {}".format(self.tolerance)
        self.lblTolerance.setText(str)

        layoutTolerance = QHBoxLayout()
        layoutTolerance.addWidget(self.lblTolerance)
        layoutTolerance.addWidget(self.sliderTolerance)

        self.viewerplus = QtImageViewerPlus()
        self.viewerplus.disableScrollBars()
        self.viewerplus.setFixedWidth(IMAGEVIEWER_SIZE)
        self.viewerplus.setFixedHeight(IMAGEVIEWER_SIZE)

        self.btnCancel = QPushButton("Cancel")
        self.btnCancel.setAutoFillBackground(True)

        self.btnApply = QPushButton("Apply")
        self.btnApply.setAutoFillBackground(True)

        layoutButtons = QHBoxLayout()
        layoutButtons.addWidget(self.btnCancel)
        layoutButtons.addWidget(self.btnApply)

        layoutV = QVBoxLayout()
        layoutV.addLayout(layoutTolerance)
        layoutV.addWidget(self.viewerplus)
        layoutV.addLayout(layoutButtons)
        layoutV.setSpacing(10)
        self.setLayout(layoutV)

        self.viewerplus.setImage(self.qimg_cropped)
        self.preview()

        self.setAutoFillBackground(True)

        self.setWindowTitle("Crack")


    def keyPressEvent(self, event):

        if event.key() == Qt.Key_Escape:

            # RESET CURRENT OPERATION
            self.closeCrackWidget.emit()


    @pyqtSlot()
    def sliderToleranceChanged(self):

        # update tolerance value
        newvalue = self.sliderTolerance.value()
        str1 = "Tolerance {}".format(newvalue)
        self.lblTolerance.setText(str1)
        self.tolerance = newvalue

        # update the preview of the crack segmentation
        self.preview()

    @pyqtSlot()
    def preview(self):

        arr = self.input_arr.copy()
        mask_crack = self.blob.createCrack(arr, self.xmap, self.ymap, self.tolerance, preview=True)
        self.qimg_crack = utils.maskToQImage(mask_crack)
        self.viewerplus.setOpacity(0.5)
        self.viewerplus.setOverlayImage(self.qimg_crack)


    def apply(self):

        mask_crack = self.blob.createCrack(self.input_arr, self.xmap, self.ymap, self.tolerance, preview=False)
Exemplo n.º 51
0
class MainWidget(QWidget):
    def __init__(self, Parent=None):
        super().__init__(Parent)
        self.__InitData()
        self.__InitView()
        f = open("params15000.json", "r")
        data = json.load(f)
        f.close()
        self.biase = np.array(data["biase"])
        self.w_in = np.array(data["w_in"])
        self.w_out = np.array(data["w_out"])
    def __InitData(self):
        self.__paintBoard = PaintBoard(self)
        self.__colorList = QColor.colorNames()
    def __InitView(self):
        # self.setFixedSize(640,480)
        # self.setFixedSize(480,410)
        self.setFixedSize(800, 618)
        self.setWindowTitle("Handwritten Digit Recognition Based on HOG-ELM")
        self.setWindowIcon(QIcon('ICON.ico'))
        main_layout = QHBoxLayout(self)
        main_layout.setSpacing(10)
        main_layout.addWidget(self.__paintBoard)
        self.font = QtGui.QFont()
        self.font.setFamily("Consolas")
        self.font.setPointSize(15)
        sub_layout = QVBoxLayout()
        sub_layout.setContentsMargins(10, 10, 10, 10)
        self.__btn_Clear = QPushButton("Clear Board")
        self.__btn_Clear.setParent(self)
        self.__btn_Clear.setFixedSize(146, 70)
        self.__btn_Clear.setFont(self.font)
        self.__btn_Clear.clicked.connect(self.__paintBoard.Clear)
        sub_layout.addWidget(self.__btn_Clear)
        self.__btn_Quit = QPushButton("Exit")
        self.__btn_Quit.setParent(self)
        self.__btn_Quit.setFixedSize(146, 70)
        self.__btn_Quit.setFont(self.font)
        self.__btn_Quit.clicked.connect(self.Quit)
        sub_layout.addWidget(self.__btn_Quit)
        self.__btn_Save = QPushButton("Save Board")
        self.__btn_Save.setParent(self)
        self.__btn_Save.setFixedSize(146, 70)
        self.__btn_Save.setFont(self.font)
        self.__btn_Save.clicked.connect(self.on_btn_Save_Clicked)
        sub_layout.addWidget(self.__btn_Save)
        self.__cbtn_Eraser = QCheckBox("Eraser")
        self.__cbtn_Eraser.setParent(self)
        self.__cbtn_Eraser.setFont(self.font)
        self.__cbtn_Eraser.clicked.connect(self.on_cbtn_Eraser_clicked)
        sub_layout.addWidget(self.__cbtn_Eraser)
        self.__label_result = QLabel(self)
        self.__label_result.setAlignment(Qt.AlignCenter)
        self.__label_result.setFixedWidth(146)
        self.__label_result.setFixedHeight(80)
        self.__label_result.setFrameStyle(PyQt5.QtWidgets.QFrame.Box)
        self.__label_result.setFrameShadow(PyQt5.QtWidgets.QFrame.Raised)
        self.__label_result.setLineWidth(6)
        self.__label_result.setMidLineWidth(5)
        self.__label_result.setStyleSheet('background-color: rgb(255,123,100)')
        sub_layout.addWidget(self.__label_result)
        self.__btn_Recognize = QPushButton("Recognition")
        self.__btn_Recognize.setParent(self)
        self.__btn_Recognize.setFixedSize(146, 70)
        self.__btn_Recognize.setFont(self.font)
        self.__btn_Recognize.clicked.connect(self.on_btn_Recognize_clicked)
        sub_layout.addWidget(self.__btn_Recognize)
        self.__label_timage = QLabel(self)
        self.__label_timage.setAlignment(Qt.AlignCenter)
        self.__label_timage.setFixedWidth(146)
        self.__label_timage.setFixedHeight(80)
        self.__label_timage.setFrameStyle(PyQt5.QtWidgets.QFrame.Box)
        self.__label_timage.setFrameShadow(PyQt5.QtWidgets.QFrame.Raised)
        self.__label_timage.setLineWidth(6)
        self.__label_timage.setMidLineWidth(5)
        self.__label_timage.setStyleSheet('background-color: rgb(125,143,50)')
        sub_layout.addWidget(self.__label_timage)
        self.__btn_Random = QPushButton("RandomDigit \nFrom TestSet")
        self.__btn_Random.setParent(self)
        self.__btn_Random.setFixedSize(146, 70)
        self.font.setPointSize(13)
        self.__btn_Random.setFont(self.font)
        self.__btn_Random.clicked.connect(self.on_btn_RandomDigit_Clicked)
        sub_layout.addWidget(self.__btn_Random)
        main_layout.addLayout(sub_layout)
    def __fillColorList(self, comboBox):
        index_black = 0
        index = 0
        for color in self.__colorList:
            if color == "black":
                index_black = index
            index += 1
            pix = QPixmap(70, 20)
            pix.fill(QColor(color))
            comboBox.addItem(QIcon(pix), None)
            comboBox.setIconSize(QSize(70, 20))
            comboBox.setSizeAdjustPolicy(QComboBox.AdjustToContents)
        comboBox.setCurrentIndex(index_black)
    def on_PenColorChange(self):
        color_index = self.__comboBox_penColor.currentIndex()
        color_str = self.__colorList[color_index]
        self.__paintBoard.ChangePenColor(color_str)
    def on_PenThicknessChange(self):
        penThickness = self.__spinBox_penThickness.value()
        self.__paintBoard.ChangePenThickness(penThickness)
    def on_btn_Save_Clicked(self):
        savePath = QFileDialog.getSaveFileName(self, 'Save Your Paint', '.\\', '*.png')
        print(savePath)
        if savePath[0] == "":
            print("Save cancel")
            return
        image = self.__paintBoard.GetContentAsQImage()
        image.save(savePath[0])
    def on_cbtn_Eraser_clicked(self):
        if self.__cbtn_Eraser.isChecked():
            self.__paintBoard.EraserMode = True
        else:
            self.__paintBoard.EraserMode = False
    def on_btn_RandomDigit_Clicked(self):
        f = open('x_test_10000.pkl', 'rb')
        x_test = pickle.load(f, encoding='bytes')
        f.close()
        ff = open('y_test_10000.pkl', 'rb')
        y_test = pickle.load(ff, encoding='bytes')
        ff.close()
        random_id = random.randint(0, 9999)
        image = Image.fromarray(np.reshape(x_test[random_id], (28, 28)) * 255).convert('L')
        new_image = image.resize((44, 44))
        # new_image.show()
        new_image.save('tpic.png')
        pixmap = QPixmap('tpic.png')
        self.__label_timage.setPixmap(pixmap)
        res = self.judge(np.reshape(x_test[random_id], (28, 28)))
        myres = "{0}|{1}".format(res, int(y_test[random_id]))
        # show my result
        font = QtGui.QFont()
        font.setFamily('Consolas')
        font.setBold(True)
        font.setPointSize(18)
        font.setWeight(75)
        self.__label_result.setFont(font)
        self.__label_result.setText(myres)
    def sigmoid(self, x):
        return 1.0 / (1.0 + np.exp(-x))
    def judge(self, input_v):
        fd = hog(input_v,
                 orientations=5,
                 pixels_per_cell=(4, 4),
                 cells_per_block=(3, 3),
                 block_norm='L1-sqrt',
                 transform_sqrt=True,
                 feature_vector=True,
                 visualise=False
                 )
        length = len(fd)
        y_hat = np.dot(self.w_out,
                       self.sigmoid(np.dot(self.w_in, np.reshape(fd, (length, 1))) + self.biase.transpose()))
        res_id = np.argmax(y_hat)
        y_hat[y_hat < 0] = 0
        prapability = y_hat[res_id] / np.sum(y_hat)
        myres = "{0}({1}%)".format(res_id, int(prapability * 100))
        return myres
    def on_btn_Recognize_clicked(self):
        savePath = "tmp.png"
        image = self.__paintBoard.GetContentAsQImage()
        image.save(savePath)
        t_image = Image.open(savePath).convert('L')
        newt_image = t_image.resize((28, 28))
        # newt_image.save("tmp1.png")
        np_image = np.array(newt_image) / 255.0
        # print (np_image.shape)
        # print (np_image)
        myres = self.judge(np_image)
        # show my result
        font = QtGui.QFont()
        font.setFamily('Consolas')
        font.setBold(True)
        font.setPointSize(20)
        font.setWeight(75)
        self.__label_result.setFont(font)
        self.__label_result.setText(myres)
        # print (myres)
    def Quit(self):
        self.close()
Exemplo n.º 52
0
    def __init__(self, window, plugin, keystore, device_id):
        title = _("{} Settings").format(plugin.device)
        super(SettingsDialog, self).__init__(window, title)
        self.setMaximumWidth(540)

        devmgr = plugin.device_manager()
        config = devmgr.config
        handler = keystore.handler
        thread = keystore.thread
        hs_cols, hs_rows = (128, 64)

        def invoke_client(method, *args, **kw_args):
            unpair_after = kw_args.pop('unpair_after', False)

            def task():
                client = devmgr.client_by_id(device_id)
                if not client:
                    raise RuntimeError("Device not connected")
                if method:
                    getattr(client, method)(*args, **kw_args)
                if unpair_after:
                    devmgr.unpair_id(device_id)
                return client.features

            thread.add(task, on_success=update)

        def update(features):
            self.features = features
            set_label_enabled()
            if features.bootloader_hash:
                bl_hash = bh2u(features.bootloader_hash)
                bl_hash = "\n".join([bl_hash[:32], bl_hash[32:]])
            else:
                bl_hash = "N/A"
            noyes = [_("No"), _("Yes")]
            endis = [_("Enable Passphrases"), _("Disable Passphrases")]
            disen = [_("Disabled"), _("Enabled")]
            setchange = [_("Set a PIN"), _("Change PIN")]

            version = "%d.%d.%d" % (features.major_version,
                                    features.minor_version,
                                    features.patch_version)

            device_label.setText(features.label)
            pin_set_label.setText(noyes[features.pin_protection])
            passphrases_label.setText(disen[features.passphrase_protection])
            bl_hash_label.setText(bl_hash)
            label_edit.setText(features.label)
            device_id_label.setText(features.device_id)
            initialized_label.setText(noyes[features.initialized])
            version_label.setText(version)
            clear_pin_button.setVisible(features.pin_protection)
            clear_pin_warning.setVisible(features.pin_protection)
            pin_button.setText(setchange[features.pin_protection])
            pin_msg.setVisible(not features.pin_protection)
            passphrase_button.setText(endis[features.passphrase_protection])
            language_label.setText(features.language)

        def set_label_enabled():
            label_apply.setEnabled(label_edit.text() != self.features.label)

        def rename():
            invoke_client('change_label', label_edit.text())

        def toggle_passphrase():
            title = _("Confirm Toggle Passphrase Protection")
            currently_enabled = self.features.passphrase_protection
            if currently_enabled:
                msg = _("After disabling passphrases, you can only pair this "
                        "Electrum wallet if it had an empty passphrase.  "
                        "If its passphrase was not empty, you will need to "
                        "create a new wallet with the install wizard.  You "
                        "can use this wallet again at any time by re-enabling "
                        "passphrases and entering its passphrase.")
            else:
                msg = _("Your current Electrum wallet can only be used with "
                        "an empty passphrase.  You must create a separate "
                        "wallet with the install wizard for other passphrases "
                        "as each one generates a new set of addresses.")
            msg += "\n\n" + _("Are you sure you want to proceed?")
            if not self.question(msg, title=title):
                return
            invoke_client('toggle_passphrase', unpair_after=currently_enabled)

        def change_homescreen():
            dialog = QFileDialog(self, _("Choose Homescreen"))
            filename, __ = dialog.getOpenFileName()
            if not filename:
                return  # user cancelled

            if filename.endswith('.toif'):
                img = open(filename, 'rb').read()
                if img[:8] != b'TOIf\x90\x00\x90\x00':
                    handler.show_error(
                        'File is not a TOIF file with size of 144x144')
                    return
            else:
                from PIL import Image  # FIXME
                im = Image.open(filename)
                if im.size != (128, 64):
                    handler.show_error('Image must be 128 x 64 pixels')
                    return
                im = im.convert('1')
                pix = im.load()
                img = bytearray(1024)
                for j in range(64):
                    for i in range(128):
                        if pix[i, j]:
                            o = (i + j * 128)
                            img[o // 8] |= (1 << (7 - o % 8))
                img = bytes(img)
            invoke_client('change_homescreen', img)

        def clear_homescreen():
            invoke_client('change_homescreen', b'\x00')

        def set_pin():
            invoke_client('set_pin', remove=False)

        def clear_pin():
            invoke_client('set_pin', remove=True)

        def wipe_device():
            wallet = window.wallet
            if wallet and sum(wallet.get_balance()):
                title = _("Confirm Device Wipe")
                msg = _("Are you SURE you want to wipe the device?\n"
                        "Your wallet still has bitcoins in it!")
                if not self.question(
                        msg, title=title, icon=QMessageBox.Critical):
                    return
            invoke_client('wipe_device', unpair_after=True)

        def slider_moved():
            mins = timeout_slider.sliderPosition()
            timeout_minutes.setText(_("{:2d} minutes").format(mins))

        def slider_released():
            config.set_session_timeout(timeout_slider.sliderPosition() * 60)

        # Information tab
        info_tab = QWidget()
        info_layout = QVBoxLayout(info_tab)
        info_glayout = QGridLayout()
        info_glayout.setColumnStretch(2, 1)
        device_label = QLabel()
        pin_set_label = QLabel()
        passphrases_label = QLabel()
        version_label = QLabel()
        device_id_label = QLabel()
        bl_hash_label = QLabel()
        bl_hash_label.setWordWrap(True)
        language_label = QLabel()
        initialized_label = QLabel()
        rows = [
            (_("Device Label"), device_label),
            (_("PIN set"), pin_set_label),
            (_("Passphrases"), passphrases_label),
            (_("Firmware Version"), version_label),
            (_("Device ID"), device_id_label),
            (_("Bootloader Hash"), bl_hash_label),
            (_("Language"), language_label),
            (_("Initialized"), initialized_label),
        ]
        for row_num, (label, widget) in enumerate(rows):
            info_glayout.addWidget(QLabel(label), row_num, 0)
            info_glayout.addWidget(widget, row_num, 1)
        info_layout.addLayout(info_glayout)

        # Settings tab
        settings_tab = QWidget()
        settings_layout = QVBoxLayout(settings_tab)
        settings_glayout = QGridLayout()

        # Settings tab - Label
        label_msg = QLabel(
            _("Name this {}.  If you have multiple devices "
              "their labels help distinguish them.").format(plugin.device))
        label_msg.setWordWrap(True)
        label_label = QLabel(_("Device Label"))
        label_edit = QLineEdit()
        label_edit.setMinimumWidth(150)
        label_edit.setMaxLength(plugin.MAX_LABEL_LEN)
        label_apply = QPushButton(_("Apply"))
        label_apply.clicked.connect(rename)
        label_edit.textChanged.connect(set_label_enabled)
        settings_glayout.addWidget(label_label, 0, 0)
        settings_glayout.addWidget(label_edit, 0, 1, 1, 2)
        settings_glayout.addWidget(label_apply, 0, 3)
        settings_glayout.addWidget(label_msg, 1, 1, 1, -1)

        # Settings tab - PIN
        pin_label = QLabel(_("PIN Protection"))
        pin_button = QPushButton()
        pin_button.clicked.connect(set_pin)
        settings_glayout.addWidget(pin_label, 2, 0)
        settings_glayout.addWidget(pin_button, 2, 1)
        pin_msg = QLabel(
            _("PIN protection is strongly recommended.  "
              "A PIN is your only protection against someone "
              "stealing your bitcoins if they obtain physical "
              "access to your {}.").format(plugin.device))
        pin_msg.setWordWrap(True)
        pin_msg.setStyleSheet("color: red")
        settings_glayout.addWidget(pin_msg, 3, 1, 1, -1)

        # Settings tab - Homescreen
        homescreen_label = QLabel(_("Homescreen"))
        homescreen_change_button = QPushButton(_("Change..."))
        homescreen_clear_button = QPushButton(_("Reset"))
        homescreen_change_button.clicked.connect(change_homescreen)
        try:
            import PIL
        except ImportError:
            homescreen_change_button.setDisabled(True)
            homescreen_change_button.setToolTip(
                _("Required package 'PIL' is not available - Please install it."
                  ))
        homescreen_clear_button.clicked.connect(clear_homescreen)
        homescreen_msg = QLabel(
            _("You can set the homescreen on your "
              "device to personalize it.  You must "
              "choose a {} x {} monochrome black and "
              "white image.").format(hs_cols, hs_rows))
        homescreen_msg.setWordWrap(True)
        settings_glayout.addWidget(homescreen_label, 4, 0)
        settings_glayout.addWidget(homescreen_change_button, 4, 1)
        settings_glayout.addWidget(homescreen_clear_button, 4, 2)
        settings_glayout.addWidget(homescreen_msg, 5, 1, 1, -1)

        # Settings tab - Session Timeout
        timeout_label = QLabel(_("Session Timeout"))
        timeout_minutes = QLabel()
        timeout_slider = QSlider(Qt.Horizontal)
        timeout_slider.setRange(1, 60)
        timeout_slider.setSingleStep(1)
        timeout_slider.setTickInterval(5)
        timeout_slider.setTickPosition(QSlider.TicksBelow)
        timeout_slider.setTracking(True)
        timeout_msg = QLabel(
            _("Clear the session after the specified period "
              "of inactivity.  Once a session has timed out, "
              "your PIN and passphrase (if enabled) must be "
              "re-entered to use the device."))
        timeout_msg.setWordWrap(True)
        timeout_slider.setSliderPosition(config.get_session_timeout() // 60)
        slider_moved()
        timeout_slider.valueChanged.connect(slider_moved)
        timeout_slider.sliderReleased.connect(slider_released)
        settings_glayout.addWidget(timeout_label, 6, 0)
        settings_glayout.addWidget(timeout_slider, 6, 1, 1, 3)
        settings_glayout.addWidget(timeout_minutes, 6, 4)
        settings_glayout.addWidget(timeout_msg, 7, 1, 1, -1)
        settings_layout.addLayout(settings_glayout)
        settings_layout.addStretch(1)

        # Advanced tab
        advanced_tab = QWidget()
        advanced_layout = QVBoxLayout(advanced_tab)
        advanced_glayout = QGridLayout()

        # Advanced tab - clear PIN
        clear_pin_button = QPushButton(_("Disable PIN"))
        clear_pin_button.clicked.connect(clear_pin)
        clear_pin_warning = QLabel(
            _("If you disable your PIN, anyone with physical access to your "
              "{} device can spend your bitcoins.").format(plugin.device))
        clear_pin_warning.setWordWrap(True)
        clear_pin_warning.setStyleSheet("color: red")
        advanced_glayout.addWidget(clear_pin_button, 0, 2)
        advanced_glayout.addWidget(clear_pin_warning, 1, 0, 1, 5)

        # Advanced tab - toggle passphrase protection
        passphrase_button = QPushButton()
        passphrase_button.clicked.connect(toggle_passphrase)
        passphrase_msg = WWLabel(PASSPHRASE_HELP)
        passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
        passphrase_warning.setStyleSheet("color: red")
        advanced_glayout.addWidget(passphrase_button, 3, 2)
        advanced_glayout.addWidget(passphrase_msg, 4, 0, 1, 5)
        advanced_glayout.addWidget(passphrase_warning, 5, 0, 1, 5)

        # Advanced tab - wipe device
        wipe_device_button = QPushButton(_("Wipe Device"))
        wipe_device_button.clicked.connect(wipe_device)
        wipe_device_msg = QLabel(
            _("Wipe the device, removing all data from it.  The firmware "
              "is left unchanged."))
        wipe_device_msg.setWordWrap(True)
        wipe_device_warning = QLabel(
            _("Only wipe a device if you have the recovery seed written down "
              "and the device wallet(s) are empty, otherwise the bitcoins "
              "will be lost forever."))
        wipe_device_warning.setWordWrap(True)
        wipe_device_warning.setStyleSheet("color: red")
        advanced_glayout.addWidget(wipe_device_button, 6, 2)
        advanced_glayout.addWidget(wipe_device_msg, 7, 0, 1, 5)
        advanced_glayout.addWidget(wipe_device_warning, 8, 0, 1, 5)
        advanced_layout.addLayout(advanced_glayout)
        advanced_layout.addStretch(1)

        tabs = QTabWidget(self)
        tabs.addTab(info_tab, _("Information"))
        tabs.addTab(settings_tab, _("Settings"))
        tabs.addTab(advanced_tab, _("Advanced"))
        dialog_vbox = QVBoxLayout(self)
        dialog_vbox.addWidget(tabs)
        dialog_vbox.addLayout(Buttons(CloseButton(self)))

        # Update information
        invoke_client(None)
class App(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Face detection")
        self.disply_width = 900
        self.display_height = 750
        self.setFixedSize(self.disply_width, self.display_height)
        # create the label that holds the image
        self.image_label = QLabel(self)
        self.image_label.resize(self.disply_width, self.display_height)
        # create a text label
        self.textLabel = QLabel('Start timer to make photo: ')

        # create the video capture thread
        self.thread = VideoThread()
        # connect its signal to the update_image slot
        self.thread.change_pixmap_signal.connect(self.update_image)
        # start the thread
        self.thread.get_app(self)
        self.thread.start()

        # create a vertical box layout and add the two labels
        vbox = QVBoxLayout()
        vbox.addWidget(self.image_label)
        vbox.addWidget(self.textLabel)
        # set the vbox layout as the widgets layout
        self.setLayout(vbox)

        self.btn1 = QPushButton("start timer", self)
        self.btn1.move(210, 700)
        self.btn1.clicked.connect(self.btn_start_timer)

        self.le = QLineEdit(self)
        self.le.move(320, 700)
        self.le.setReadOnly(True)
        self.le.resize(250, 30)

        self.btn2 = QPushButton("save all faces", self)
        self.btn2.move(700, 700)
        self.btn2.clicked.connect(self.btn_save_faces)

    def btn_start_timer(self):
        self.thread.start_timer()

    def btn_save_faces(self):
        self.thread.save_all_faces()

    @pyqtSlot(np.ndarray)
    def update_image(self, cv_img):
        """Updates the image_label with a new opencv image"""
        qt_img = self.convert_cv_qt(cv_img)
        self.image_label.setPixmap(qt_img)

    def convert_cv_qt(self, cv_img):
        """Convert from an opencv image to QPixmap"""
        rgb_image = cv2.cvtColor(cv_img, cv2.COLOR_BGR2RGB)
        h, w, ch = rgb_image.shape
        bytes_per_line = ch * w
        convert_to_Qt_format = QtGui.QImage(rgb_image.data, w, h, bytes_per_line, QtGui.QImage.Format_RGB888)
        p = convert_to_Qt_format.scaled(self.disply_width, self.display_height, Qt.KeepAspectRatio)
        return QPixmap.fromImage(p)
Exemplo n.º 54
0
    def initGrid(self):
        if self.data is None:
            return

        # This needs to be generalized to handle multiple input and output types
        self.imageLabels = []
        self.actionRows = []
        self.actionLabels = []

        for i in range(self.gridWidth):
            self.imageLabels.append(QLabel(self))

        ot = self.data.outputTypes()
        for output in ot:
            oneRow = []
            for i in range(self.gridWidth):
                labels = output[
                    "categories"] if "categories" in output else None
                cb = self.makeActionComboBox(atype=output["type"],
                                             labels=labels)
                oneRow.append(cb)
                self.actionLabels.append(cb)
            self.actionRows.append(oneRow)

        grid = QGridLayout()
        self.grid = grid
        grid.setSpacing(10)

        otypes = self.data.outputTypes()
        itypes = self.data.inputTypes()

        row = 1
        grid.addWidget(QLabel("Index"), row, 0)
        self.indexes = []
        for i in range(self.gridWidth):
            idx = QLabel(self)
            idx.setAlignment(Qt.AlignCenter)
            self.indexes.append(idx)
        for i in range(len(self.indexes)):
            grid.addWidget(self.indexes[i], row, i + 1)

        row += 1
        grid.addWidget(QLabel(itypes[0]["name"]), row, 0)
        for i in range(len(self.imageLabels)):
            grid.addWidget(self.imageLabels[i], row, i + 1)

        for lr in range(len(self.actionRows)):
            arow = self.actionRows[lr]
            row += 1
            grid.addWidget(QLabel(otypes[lr]["name"]), row, 0)
            for i in range(len(arow)):
                grid.addWidget(arow[i], row, i + 1)

        vlay = QVBoxLayout()
        vlay.addLayout(grid)
        row += 1
        sld = QSlider(Qt.Horizontal, self)
        self.slider = sld
        sld.setFocusPolicy(Qt.NoFocus)
        sld.valueChanged[int].connect(self.changeValue)
        #grid.addWidget(sld, row, 0, 1, self.gridWidth+1)
        vlay.addWidget(sld)

        self.setCentralWidget(QWidget(self))
        self.centralWidget().setLayout(vlay)

        if self.metaDock is None:
            self.metaDock = QDockWidget("Drive Info", self)
            self.addDockWidget(Qt.LeftDockWidgetArea, self.metaDock)
            self.metaText = QTextEdit(self)
            self.metaText.setEnabled(False)
            self.metaText.setReadOnly(True)
            #self.metaText.setMinimumWidth( 200.0 )
            self.metaDock.setWidget(self.metaText)
            self.viewMenu.addAction(self.metaDock.toggleViewAction())
        self.metaText.setText(self.data.metaString())

        if self.statsDock is None:
            self.statsDock = QDockWidget("Action Stats", self)
            self.addDockWidget(Qt.LeftDockWidgetArea, self.statsDock)
            self.statsTable = QTableWidget(self)
            self.statsTable.setEnabled(False)
            self.statsTable.horizontalHeader().hide()
            self.statsTable.verticalHeader().setDefaultSectionSize(18)
            self.statsTable.verticalHeader().hide()
            self.statsTable.setShowGrid(False)
            self.statsDock.setWidget(self.statsTable)
            self.viewMenu.addAction(self.statsDock.toggleViewAction())

        self.updateStats()
Exemplo n.º 55
0
class PreferencesDialog(QDialog):
    def __init__(self, threshold, correction, mean):
        self.threshold = threshold
        self.correction = correction
        self.mean = mean
        super(PreferencesDialog, self).__init__()
        self.setWindowTitle("Preferences")
        main_layout = QVBoxLayout()

        self.change_threshold()
        main_layout.addWidget(self.frame)

        self.change_correction_number()
        main_layout.addWidget(self.frame2)

        self.change_mean_number()
        main_layout.addWidget(self.frame3)

        self.create_buttons()
        main_layout.addWidget(self.buttons)

        self.setLayout(main_layout)

    # method creating a frame for changing the threshold value - validator added to ensure it's a double value
    def change_threshold(self):
        self.frame = QGroupBox("Threshold")
        thresh_layout = QGridLayout()
        thresh_layout.addWidget(QLabel("Current threshold [cm]: "), 0, 0)
        self.thresh_label = QLabel(str(self.threshold))
        thresh_layout.addWidget(self.thresh_label, 0, 1)
        thresh_layout.addWidget(QLabel("New value [cm]:"), 1, 0)

        self.textbox = QLineEdit(self)
        only_number = QDoubleValidator()
        self.textbox.setValidator(only_number)
        thresh_layout.addWidget(self.textbox, 1, 1)

        self.frame.setLayout(thresh_layout)

    # method creating a frame for changing the  number of initial sessions before the correction is applied
    # - validator added to ensure it's an integer value
    def change_correction_number(self):
        self.frame2 = QGroupBox(
            "Number of sessions before the corrections were applied")
        thresh_layout = QGridLayout()
        thresh_layout.addWidget(QLabel("Current number: "), 0, 0)
        self.correction_label = QLabel(str(self.correction))
        thresh_layout.addWidget(self.correction_label, 0, 1)
        thresh_layout.addWidget(QLabel("New value:"), 1, 0)

        self.correction_textbox = QLineEdit(self)
        only_number = QIntValidator()
        self.correction_textbox.setValidator(only_number)
        thresh_layout.addWidget(self.correction_textbox, 1, 1)

        self.frame2.setLayout(thresh_layout)

    # method creating a frame for changing the  number of sessions taken for calculating the mean and standard
    # deviation values - validator added to ensure it's an integer value
    def change_mean_number(self):
        self.frame3 = QGroupBox(
            "Number of sessions used to calculate the mean averages")
        thresh_layout = QGridLayout()
        thresh_layout.addWidget(QLabel("Current number: "), 0, 0)
        if self.mean == 0:
            self.mean_label = QLabel("All sessions")
        else:
            self.mean_label = QLabel(str(self.mean))
        thresh_layout.addWidget(self.mean_label, 0, 1)
        thresh_layout.addWidget(QLabel("New value:"), 1, 0)

        self.mean_textbox = QLineEdit(self)
        only_number = QIntValidator()
        self.mean_textbox.setValidator(only_number)
        thresh_layout.addWidget(self.mean_textbox, 1, 1)

        self.frame3.setLayout(thresh_layout)

    # method adding widget with the buttons for applying the changes
    def create_buttons(self):
        self.buttons = QWidget()
        buttons_layout = QHBoxLayout()

        apply_button = QPushButton('Apply', self)
        apply_button.clicked.connect(self.apply)
        buttons_layout.addWidget(apply_button)

        ok_button = QPushButton('Ok', self)
        ok_button.clicked.connect(self.ok)
        buttons_layout.addWidget(ok_button)

        self.buttons.setLayout(buttons_layout)

    # method readign the values and changing them in the dialog - without closing
    def apply(self):
        thresh = self.textbox.text()
        if "," in thresh:
            thresh = thresh.replace(",", ".")
        try:
            val = float(thresh)
            self.threshold = val
            self.thresh_label.setText(str(self.threshold))
        except ValueError:
            pass

        cor = self.correction_textbox.text()
        try:
            val = int(cor)
            self.correction = val
            self.correction_label.setText(str(self.correction))
        except ValueError:
            pass

        mean = self.mean_textbox.text()
        try:
            val = int(mean)
            self.mean = val
            if val == 0:
                self.mean_label.setText("All sessions")
            else:
                self.mean_label.setText(str(self.mean))
        except ValueError:
            pass

    # method readign the values and changing them in the dialog - with closing
    def ok(self):
        thresh = self.textbox.text()
        if "," in thresh:
            thresh = thresh.replace(",", ".")
        try:
            val = float(thresh)
            self.threshold = val
        except ValueError:
            pass

        cor = self.correction_textbox.text()
        try:
            val = int(cor)
            self.correction = val
        except ValueError:
            pass

        mean = self.mean_textbox.text()
        try:
            val = int(mean)
            self.mean = val
        except ValueError:
            pass

        self.close()

    def get_threshold(self):
        return self.threshold

    def get_correction_sessions(self):
        return self.correction

    def get_mean_sessions(self):
        return self.mean
Exemplo n.º 56
0
 def _widgets(self):
   '''
   Create widgets into tab.
   '''
   style = '''
     QLabel {
       font-weight: bold;
     }
   '''
   
   # io
   io_l = QLabel('I/O Interface', self)
   io_l.setStyleSheet(style)
   self.layout.addWidget(io_l, 0, 0, 1, 2, Qt.AlignTop | Qt.AlignCenter)
   self.io_cb = QComboBox(self)
   self.io_cb.addItems(('read', 'mmap'))
   self.io_cb.setEnabled(False)
   self.layout.addWidget(self.io_cb, 1, 0, 1, 2, Qt.AlignTop)
   
   # separator
   sep = QFrame(self)
   sep.setFrameShape(QFrame.HLine)
   sep.setFrameShadow(QFrame.Sunken)
   sep.setLineWidth(1)
   sep.setMidLineWidth(0)
   self.layout.addWidget(sep, 2, 0, 1, 2, Qt.AlignTop)
   
   # fps
   fps_l = QLabel('Frames per second', self)
   fps_l.setStyleSheet(style)
   self.layout.addWidget(fps_l, 3, 0, 1, 2, Qt.AlignTop | Qt.AlignCenter)
   self.fps_cb = QComboBox(self)
   self.layout.addWidget(self.fps_cb, 4, 0, 1, 2, Qt.AlignTop | Qt.AlignCenter)
   
   # crop
   crop_l = QLabel('Cropping', self)
   crop_l.setStyleSheet(style)
   self.layout.addWidget(crop_l, 5, 0, 1, 2, Qt.AlignTop | Qt.AlignCenter)
   ## top
   top_l = QLabel('Top', self)
   top_l.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Preferred)
   self.layout.addWidget(top_l, 6, 0, 1, 1, Qt.AlignTop)
   self.crop_t_sb = QSpinBox(self)
   self.layout.addWidget(self.crop_t_sb, 6, 1, 1, 1, Qt.AlignTop)
   ## left
   left_l = QLabel('Left', self)
   left_l.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Preferred)
   self.layout.addWidget(left_l, 7, 0, 1, 1, Qt.AlignTop)
   self.crop_l_sb = QSpinBox(self)
   self.layout.addWidget(self.crop_l_sb, 7, 1, 1, 1, Qt.AlignTop)
   ## width
   width_l = QLabel('Width', self)
   width_l.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Preferred)
   self.layout.addWidget(width_l, 8, 0, 1, 1, Qt.AlignTop)
   self.crop_w_sb = QSpinBox(self)
   self.layout.addWidget(self.crop_w_sb, 8, 1, 1, 1, Qt.AlignTop)
   ## height
   height_l = QLabel('Height', self)
   height_l.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Preferred)
   self.layout.addWidget(height_l, 9, 0, 1, 1, Qt.AlignTop)
   self.crop_h_sb = QSpinBox(self)
   self.layout.addWidget(self.crop_h_sb, 9, 1, 1, 1, Qt.AlignTop)
   
   # format
   format_l = QLabel('Window size', self)
   format_l.setStyleSheet(style)
   self.layout.addWidget(format_l, 10, 0, 1, 2, Qt.AlignTop | Qt.AlignCenter)
   ## width
   fwidth_l = QLabel('Width', self)
   fwidth_l.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Preferred)
   self.layout.addWidget(fwidth_l, 11, 0, 1, 1, Qt.AlignTop)
   self.format_w_sb = QSpinBox(self)
   self.layout.addWidget(self.format_w_sb, 11, 1, 1, 1, Qt.AlignTop)
   ## height
   fheight_l = QLabel('Height', self)
   fheight_l.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Preferred)
   self.layout.addWidget(fheight_l, 12, 0, 1, 1, Qt.AlignTop)
   self.format_h_sb = QSpinBox(self)
   self.layout.addWidget(self.format_h_sb, 12, 1, 1, 1, Qt.AlignTop)
Exemplo n.º 57
0
"""Пример расположения с помощью сетки"""

import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QWidget  #представляет из себя одно окно
from PyQt5.QtWidgets import QLineEdit  #кнопочки, на которые можно нажимать
from PyQt5.QtWidgets import QPushButton  #кнопочки, на которые можно нажимать
from PyQt5.QtWidgets import QLabel  #кнопочки, на которые можно нажимать
from PyQt5.QtWidgets import QFormLayout  #кнопочки, на которые можно нажимать

app = QApplication(sys.argv)

window = QWidget()
window.setWindowTitle("Первая программа на PyQt5")
window.setGeometry(400, 400, 600, 600)

layout = QFormLayout()  #Создаем объект верстки
"""первый аргумент строка, второй - позиция в ней"""
layout.addRow(QLabel("Enter you IDs"))
layout.addRow("Name", QLineEdit())
layout.addRow("Surname", QLineEdit())
layout.addRow("Card Number", QLineEdit())
layout.addRow(QPushButton("Send data"))

window.setLayout(layout)
window.show()
sys.exit(app.exec())
Exemplo n.º 58
0
    def __init__(self,
                 msg,
                 kind,
                 OK_button,
                 wallet=None,
                 force_disable_encrypt_cb=False):
        self.wallet = wallet

        self.pw = QLineEdit()
        self.pw.setEchoMode(2)
        self.new_pw = QLineEdit()
        self.new_pw.setEchoMode(2)
        self.conf_pw = QLineEdit()
        self.conf_pw.setEchoMode(2)
        self.kind = kind
        self.OK_button = OK_button

        vbox = QVBoxLayout()
        label = QLabel(msg + "\n")
        label.setWordWrap(True)

        grid = QGridLayout()
        grid.setSpacing(8)
        grid.setColumnMinimumWidth(0, 150)
        grid.setColumnMinimumWidth(1, 100)
        grid.setColumnStretch(1, 1)

        if kind == PW_PASSPHRASE:
            vbox.addWidget(label)
            msgs = [_('Passphrase:'), _('Confirm Passphrase:')]
        else:
            logo_grid = QGridLayout()
            logo_grid.setSpacing(8)
            logo_grid.setColumnMinimumWidth(0, 70)
            logo_grid.setColumnStretch(1, 1)

            logo = QLabel()
            logo.setAlignment(Qt.AlignCenter)

            logo_grid.addWidget(logo, 0, 0)
            logo_grid.addWidget(label, 0, 1, 1, 2)
            vbox.addLayout(logo_grid)

            m1 = _('New Password:'******'Password:'******'Confirm Password:'******'Current Password:'******'Encrypt wallet file'))
        self.encrypt_cb.setEnabled(False)
        grid.addWidget(self.encrypt_cb, 4, 0, 1, 2)
        self.encrypt_cb.setVisible(kind != PW_PASSPHRASE)

        def enable_OK():
            ok = self.new_pw.text() == self.conf_pw.text()
            OK_button.setEnabled(ok)
            self.encrypt_cb.setEnabled(ok and bool(self.new_pw.text())
                                       and not force_disable_encrypt_cb)

        self.new_pw.textChanged.connect(enable_OK)
        self.conf_pw.textChanged.connect(enable_OK)

        self.vbox = vbox
Exemplo n.º 59
0
 def _widgets(self):
   '''
   Create widgets into tab.
   '''
   style = '''
     QLabel {
       font-weight: bold;
     }
   '''
   
   # filename
   filename_l = QLabel('Streaming address', self)
   filename_l.setStyleSheet(style)
   self.layout.addWidget(filename_l, 0, 0, 1, 7, Qt.AlignTop | Qt.AlignCenter)
   ## ip
   ip_l = QLabel('udp://', self)
   ip_l.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Preferred)
   self.layout.addWidget(ip_l, 1, 0, 1, 1, Qt.AlignTop)
   self.ip_1_sb = QSpinBox(self)
   self.ip_1_sb.setRange(239, 239)
   self.layout.addWidget(self.ip_1_sb, 1, 1, 1, 1, Qt.AlignTop)
   self.ip_2_sb = QSpinBox(self)
   self.ip_2_sb.setRange(0, 254)
   self.layout.addWidget(self.ip_2_sb, 1, 2, 1, 1, Qt.AlignTop)
   self.ip_3_sb = QSpinBox(self)
   self.ip_3_sb.setRange(0, 254)
   self.layout.addWidget(self.ip_3_sb, 1, 3, 1, 1, Qt.AlignTop)
   self.ip_4_sb = QSpinBox(self)
   self.ip_4_sb.setRange(1, 254)
   self.layout.addWidget(self.ip_4_sb, 1, 4, 1, 1, Qt.AlignTop)
   ## port
   port_l = QLabel(':', self)
   port_l.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Preferred)
   self.layout.addWidget(port_l, 1, 5, 1, 1, Qt.AlignTop)
   self.port_sb = QSpinBox(self)
   self.port_sb.setRange(1025, 65535)
   self.layout.addWidget(self.port_sb, 1, 6, 1, 1, Qt.AlignTop)
   
   # separator
   sep = QFrame(self)
   sep.setFrameShape(QFrame.HLine)
   sep.setFrameShadow(QFrame.Sunken)
   sep.setLineWidth(1)
   sep.setMidLineWidth(0)
   self.layout.addWidget(sep, 2, 0, 1, 7)
   
   # streaming parameters
   str_l = QLabel('Streaming settings', self)
   str_l.setStyleSheet(style)
   self.layout.addWidget(str_l, 3, 0, 1, 7, Qt.AlignTop | Qt.AlignCenter)
   
   # crf
   crf_l = QLabel('Constant Rate Factor', self)
   self.layout.addWidget(crf_l, 4, 0, 1, 7, Qt.AlignCenter)
   crf_sl_l = QLabel(self)
   crf_sl_l.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Preferred)
   self.layout.addWidget(crf_sl_l, 5, 0, 1, 1, Qt.AlignTop)
   self.crf_sl = QSlider(Qt.Horizontal, self)
   self.crf_sl.setTickPosition(QSlider.TicksLeft)
   self.crf_sl.setInvertedAppearance(True)
   self.crf_sl.setRange(1, 51)
   self.crf_sl.valueChanged.connect(
     lambda e:
       crf_sl_l.setText(str(e))
   )
   self.layout.addWidget(self.crf_sl, 5, 1, 1, 6, Qt.AlignTop)
   
   # muxer
   mux_l = QLabel('Container', self)
   self.layout.addWidget(mux_l, 6, 0, 1, 7, Qt.AlignCenter)
   self.mux_cb = QComboBox(self)
   #self.mux_cb.setEnabled(False)
   self.mux_cb.addItems((
     'mpegts',
     #'matroska',
     #'ogg',
     #'mp4',
     'avi',
     #'nut',
   ))
   self.layout.addWidget(self.mux_cb, 7, 0, 1, 7, Qt.AlignCenter)
   
   # preset
   pres_l = QLabel('H.264 Preset', self)
   self.layout.addWidget(pres_l, 8, 0, 1, 7, Qt.AlignCenter)
   self.pres_cb = QComboBox(self)
   self.pres_cb.addItems((
     'ultrafast',
     'superfast',
     'veryfast',
     'faster',
     'fast',
     'medium',
     'slow',
     'slower',
     'veryslow',
     'placebo',
   ))
   self.layout.addWidget(self.pres_cb, 9, 0, 1, 7, Qt.AlignCenter)
   
   # tune
   tune_l = QLabel('H.264 Tune', self)
   self.layout.addWidget(tune_l, 10, 0, 1, 7, Qt.AlignCenter)
   self.tune_cb = QComboBox(self)
   self.tune_cb.addItems((
     'zerolatency',
     'film',
     'animation',
     'grain',
     'stillimage',
     'psnr',
     'ssim',
     'fastdecode',
   ))
   self.layout.addWidget(self.tune_cb, 11, 0, 1, 7, Qt.AlignCenter)
Exemplo n.º 60
-1
    def __init__(self, size, Id, parent=None):
        super().__init__(size, parent)

        self.id = Id

        self.box = QWidget(self)
        self.box.setGeometry(0, 0, self.width(), 240)

        self.verticalLayout = QVBoxLayout(self.box)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)

        # FadeIn
        self.groupFadeIn = QGroupBox(self.box)
        self.fadeInLayout = QGridLayout(self.groupFadeIn)

        self.fadeInSpin = QDoubleSpinBox(self.groupFadeIn)
        self.fadeInSpin.setMaximum(3600)
        self.fadeInLayout.addWidget(self.fadeInSpin, 0, 0)

        self.fadeInLabel = QLabel(self.groupFadeIn)
        self.fadeInLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.fadeInLayout.addWidget(self.fadeInLabel, 0, 1)

        self.fadeInCombo = QComboBox(self.groupFadeIn)
        self.fadeInCombo.setItemDelegate(QStyledItemDelegate())
        for key in sorted(self.FadeIn.keys()):
            self.fadeInCombo.addItem(self.FadeIn[key], key)
        self.fadeInLayout.addWidget(self.fadeInCombo, 1, 0)

        self.fadeInExpLabel = QLabel(self.groupFadeIn)
        self.fadeInExpLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.fadeInLayout.addWidget(self.fadeInExpLabel, 1, 1)

        self.verticalLayout.addWidget(self.groupFadeIn)

        # FadeOut
        self.groupFadeOut = QGroupBox(self.box)
        self.fadeOutLayout = QGridLayout(self.groupFadeOut)

        self.fadeOutSpin = QDoubleSpinBox(self.groupFadeOut)
        self.fadeOutSpin.setMaximum(3600)
        self.fadeOutLayout.addWidget(self.fadeOutSpin, 0, 0)

        self.fadeOutLabel = QLabel(self.groupFadeOut)
        self.fadeOutLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.fadeOutLayout.addWidget(self.fadeOutLabel, 0, 1)

        self.fadeOutCombo = QComboBox(self.groupFadeOut)
        self.fadeOutCombo.setItemDelegate(QStyledItemDelegate())
        for key in sorted(self.FadeOut.keys()):
            self.fadeOutCombo.addItem(self.FadeOut[key], key)
        self.fadeOutLayout.addWidget(self.fadeOutCombo, 1, 0)

        self.fadeOutExpLabel = QLabel(self.groupFadeOut)
        self.fadeOutExpLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.fadeOutLayout.addWidget(self.fadeOutExpLabel, 1, 1)

        self.verticalLayout.addWidget(self.groupFadeOut)

        self.retranslateUi()