Beispiel #1
0
    def mouseMoveEvent(self, event):
        """ QWidget.mouseMoveEvent(QMouseEvent) 
        :type event: PyQt5.QtGui.QMouseEvent.QMouseEvent
        """

        if not self.ready:
            return

        if self.move_skip:
            self.move_skip = False
            return

        if not self.start_pos:
            self.start_pos = event.globalPos()

        if self.left or self.right:
            self.move_skip = True
            QCursor.setPos(self.start_pos)

        else:
            self.start_pos = None

        if self.start_pos is not None:
            self._move_mouse(self.start_pos.x() - event.globalPos().x(),
                             self.start_pos.y() - event.globalPos().y(),
                             str(self.left).lower(), str(self.midle).lower(), str(self.right).lower())
Beispiel #2
0
    def pasteClipboard(self):
        """
        """
        if self.clip_board is None:
            return
        doc = self.manager.document
        part_item = self.part_item
        part = part_item.part()
        sgv = self.slice_graphics_view

        #  1. get mouse point at the paste
        qc = QCursor()
        global_pos = qc.pos()
        view_pt = sgv.mapFromGlobal(global_pos)
        s_pt = sgv.mapToScene(view_pt)

        to_pt = part_item.mapFromScene(s_pt)
        # print("To Grid Point", to_pt.x(), to_pt.y())

        # self.vhi_hint_item.setParentItem(part_item)
        # self.setHintPos(to_pt)
        # self.vhi_hint_item.show()

        # 2. Calculate a delta from the CORNER of the selection box
        sf = part_item.scaleFactor()
        delta = to_pt - self.copy_pt
        distance_offset  = delta.x()/sf, -delta.y()/sf

        part_instance = self.part_item.partInstance()
        new_vh_set = v3decode.importToPart( part_instance,
                                            self.clip_board,
                                            offset=distance_offset)
        self.modelClearSelected()
Beispiel #3
0
    def evaluate(self):
        if not self.videoPlaybackWidget.isOpened():
            return

        qimg = misc.cvMatToQImage(self.cv_img)
        pixmapItem = QGraphicsPixmapItem(QPixmap.fromImage(qimg))
        pixmapItem.setOpacity(0.2)

        self.frameBuffer.put(pixmapItem)
        self.frameBufferItemGroup.addToGroup(pixmapItem)
        if self.frameBuffer.qsize() > 10:
            item = self.frameBuffer.get()
            self.frameBufferItemGroup.removeFromGroup(item)
        """
        if self.trackingPathGroup is not None:
            self.trackingPathGroup.setPoints(self.currentFrameNo)
        """

        if self.handInputSystem is not None:
            self.handInputSystem.setPoints(self.currentFrameNo)
            if self.drawingFlag is True:
                mousePosition = QCursor().pos()
                mousePosition = self.inputGraphicsView.mapFromGlobal(mousePosition)
                mousePosition = self.inputGraphicsView.mapToScene(mousePosition)
                pos = [mousePosition.x(),mousePosition.y()]
                self.handInputSystem.appendPosition(pos,self.currentFrameNo)
Beispiel #4
0
    def mousePressEvent(self, event):
        """
        Handler for mouse press events.

        Keyword arguments:
        event -- mouse event
        """
        print("Click")
        super(ChainScene, self).mousePressEvent(event)
        if event.button() == Qt.LeftButton:
            if self.mode == ChainScene.InsertItem:
                item = MetaElement(self.toInsert.leftConnectorType,
                                   self.toInsert.rightConnectorType,
                                   self.toInsert.elementName,
                                   self.toInsert.color)
                item.addProperties(self.toInsert.properties)
                self.addItem(item)
                item.setPos(event.scenePos())
                self.itemInserted.emit(item)
                self.update()
                self.clearSelection()
            elif self.mode == ChainScene.InsertLine:
                self.line = QGraphicsLineItem(QLineF(event.scenePos(), event.scenePos()))
                self.addItem(self.line)
            elif self.mode == ChainScene.MoveItem:
                if self.focusItem() is None:
                    self.clearSelection()
                    self.clearFocus()
        elif event.button() == Qt.RightButton:
            if len(self.selectedItems()) > 0:
                if isinstance(self.selectedItems()[0], MetaElement):
                    self.contextMenu1.exec(QCursor.pos())
                elif isinstance(self.selectedItems()[0], Connection):
                    self.contextMenu2.exec(QCursor.pos())
Beispiel #5
0
    def mousePressEvent(self, e):
        if not self.menu.is_active and not self.game_over:
            if e.buttons() == Qt.LeftButton and QCursor.pos().x() - self.geometry().x() < 560:
                square = int((QCursor.pos().x() - self.geometry().x()) / self.board.side_of_square), \
                           int((QCursor.pos().y() - self.geometry().y()) / self.board.side_of_square)
                if not self.board.button_pressed:
                    if self.board.field.coords[square[1]][square[0]] is not None and self.board.field.coords[square[1]][square[0]].color == self.board.info.color:
                        self.board.button_pressed = True
                        self.board.pressed_piece = square[1], square[0]
                        self.board.painted_squares = right_moves(square[1], square[0], self.board.field)
                        self.board.painted_squares.append((square[1], square[0]))
                else:
                    doing_move((self.board.pressed_piece[0], self.board.pressed_piece[1]),
                               (square[1], square[0]),
                               self.board.field, self.board.info)
                    self.board.button_pressed = False
                    self.board.painted_squares = []
                    self.board.pressed_piece = None
                    pawn = pawn_can_transform(self.board.field)
                    if pawn is not None:
                        self.pawn = pawn
                        self.__transform_pawn__()
                self.repaint()

            if not self.board.vs_player and self.board.computer.color == self.board.info.color and self.pawn == None:
                self.board.computer.move()
                self.repaint()

            self.check_game_state()
Beispiel #6
0
 def __customContextMenuRequested(self, pos):
     """
     Private slot to handle the context menu request for the bookmarks tree.
     
     @param pos position the context menu was requested (QPoint)
     """
     itm = self.feedsTree.currentItem()
     if itm is None:
         return
     
     if self.feedsTree.indexOfTopLevelItem(itm) != -1:
         return
     
     urlString = itm.data(0, FeedsManager.UrlStringRole)
     if urlString:
         menu = QMenu()
         menu.addAction(
             self.tr("&Open"), self.__openMessageInCurrentTab)
         menu.addAction(
             self.tr("Open in New &Tab"), self.__openMessageInNewTab)
         menu.addSeparator()
         menu.addAction(self.tr("&Copy URL to Clipboard"),
                        self.__copyUrlToClipboard)
         menu.exec_(QCursor.pos())
     else:
         errorString = itm.data(0, FeedsManager.ErrorDataRole)
         if errorString:
             menu = QMenu()
             menu.addAction(
                 self.tr("&Show error data"), self.__showError)
             menu.exec_(QCursor.pos())
 def showDetails(self):
     """
     This method is invoked when the text on the SVG schedule is selected. Firstly
     the name of the schedule is read from the database, secondly a label is displayed
     with the text name and thirdly the schedule in the main GUI is updated to the
     chosen one from the displayed SVG file and the associated jobs displayed.
     :return: None
     """
     sched = self.webView.selectedText()
     try: name = self._sched.getSchedName(sched, self._sqlite_db)
     except KeyError: return
     #Display label with description
     label = QLabel('<font style="color: grey; background-color: yellow"><p>' + name + '</p></font>')
     label.move(QCursor.pos().x()+30,QCursor.pos().y()+20)
     label.setWindowFlags(QtCore.Qt.SplashScreen)
     label.show()
     QTimer.singleShot(10000,label.destroy)
     #set schedule selected in main parent dialog to be that selected in the graph display
     try:
         if sched != '':
             self._parent_dialog.comboBoxSched.setCurrentText(sched) #Change display of combo box
             i = self._parent_dialog.findIndex(sched) # Where in selection combo list
             self._parent_dialog.comboBoxSched.setCurrentIndex(i)
             self._parent_dialog.comboBoxSched.currentIndexChanged(i)
             self._parent_dialog.tablePopulate(i) #Populate main display
     except TypeError : pass
Beispiel #8
0
        def handleMouseMove(event):
            if self.drawingStuff:
                mouse_in_map_coords = (
                    self.ui.graphicsView.mapToScene(
                        self.ui.graphicsView.mapFromGlobal(QCursor.pos())))
                coords = list( map(lambda p: int(p),
                    [mouse_in_map_coords.x(), mouse_in_map_coords.y()]))
                coords[1] -= 1 # fix misalignment
                if self.lastMousePosOnMap is None:
                    self.lastMousePosOnMap = coords

                self.drawOnMap(self.world, self.lastMousePosOnMap[0],
                    self.lastMousePosOnMap[1], coords[0], coords[1],
                    self.ui.painterRadius.value(),
                    self.ui.painterIntensity.value() * 0.01 *\
                        anthill.WorldGenerator.default_pheromone_params.scale)
                self.lastMousePosOnMap = coords

            if self.draggingCamera:
                if self.lastMousePosGlobal is None:
                    self.lastMousePosGlobal = QCursor.pos()
                delta = QCursor.pos() - self.lastMousePosGlobal
                self.ui.graphicsView.setTransformationAnchor(
                    self.ui.graphicsView.NoAnchor)
                self.ui.graphicsView.translate(delta.x(), delta.y())
                self.lastMousePosGlobal = QCursor.pos()
Beispiel #9
0
 def onPress(self, e):
     self.isPress = True
     self.__lastX = self.widget.mapFromGlobal(QCursor.pos()).x()
     self.__lastY = self.widget.mapFromGlobal(QCursor.pos()).y()
     # print(self.widget.mapFromGlobal(QCursor.pos()).x(), QCursor.pos().x(), e.pos().x())
     if self.exPressFunc:
         e.dragObject = self
         self.exPressFunc(e)
     pass
Beispiel #10
0
    def show_menu(self):
        self.menu = Menu(right_click_menu)

        hasVideo = movie_info.movie_file != ""
        self.menu.getItemById("_fullscreen_quit").isActive = hasVideo
        self.menu.getItemById("_mini_mode").isActive = hasVideo
        self.menu.getItemById("_play_operation_forward").isActive = hasVideo
        self.menu.getItemById("_play_operation_backward").isActive = hasVideo
        self.menu.getItemById("_frame").isActive = \
            hasVideo and self._window.getState() != Qt.WindowFullScreen
        self.menu.getItemById("_subtitle_hide").isActive = \
            hasVideo and bool(movie_info.subtitle_file)
        self.menu.getItemById("_subtitle_manual").isActive = hasVideo
        self.menu.getItemById("_subtitle_choose").isActive = \
            bool(movie_info.subtitle_file)
        self.menu.getItemById("_information").isActive = hasVideo \
            and movie_info.movie_duration != 0

        self.menu.getItemById("_on_top").checked = self._window.staysOnTop

        self.menu.getItemById("proportion:radio:_p_default").checked = \
            self._proportion == "proportion:radio:_p_default"
        self.menu.getItemById("proportion:radio:_p_4_3").checked = \
            self._proportion == "proportion:radio:_p_4_3"
        self.menu.getItemById("proportion:radio:_p_16_9").checked = \
            self._proportion == "proportion:radio:_p_16_9"
        self.menu.getItemById("proportion:radio:_p_16_10").checked = \
            self._proportion == "proportion:radio:_p_16_10"
        self.menu.getItemById("proportion:radio:_p_1_85_1").checked = \
            self._proportion == "proportion:radio:_p_1_85_1"
        self.menu.getItemById("proportion:radio:_p_2_35_1").checked = \
            self._proportion == "proportion:radio:_p_2_35_1"

        self.menu.getItemById("scale:radio:_s_0_5").checked = \
            self._scale == "scale:radio:_s_0_5"
        self.menu.getItemById("scale:radio:_s_1").checked = \
            self._scale == "scale:radio:_s_1"
        self.menu.getItemById("scale:radio:_s_1_5").checked = \
            self._scale == "scale:radio:_s_1_5"
        self.menu.getItemById("scale:radio:_s_2").checked = \
            self._scale == "scale:radio:_s_2"

        self.menu.getItemById("_sound_muted").checked = config.playerMuted

        self.menu.getItemById("_subtitle_hide").checked = \
            not self._window.subtitleVisible
        subtitles = movie_info.movie_file)
        subtitles = _subtitle_menu_items_from_files(subtitles)
        self.menu.getItemById("_subtitle_choose").setSubMenu(Menu(subtitles))

        self.menu.getItemById("_fullscreen_quit").text = _("Fullscreen") if \
            self._window.getState() != Qt.WindowFullScreen else _("Exit fullscreen")
        self.menu.getItemById("_mini_mode").text = _("Exit mini mode") if \
            self._window.miniModeState() else _("Mini mode")

        self.menu.itemClicked.connect(self._menu_item_invoked)
        self.menu.showRectMenu(QCursor.pos().x(), QCursor.pos().y())
Beispiel #11
0
    def setupPuzzle(self):
        size = min(self.puzzleImage.width(), self.puzzleImage.height())
        self.puzzleImage = self.puzzleImage.copy((self.puzzleImage.width()-size)/2,
                (self.puzzleImage.height() - size)/2, size, size).scaled(400,
                        400, Qt.IgnoreAspectRatio, Qt.SmoothTransformation)

        random.seed(QCursor.pos().x() ^ QCursor.pos().y())

        self.model.addPieces(self.puzzleImage)
        self.puzzleWidget.clear()
 def showDetails(self):
     try:
         key = self.webView.selectedText()
         if key != '': name = self._db.get_node_text(key)
         else: name = ''
     except KeyError: return
     label = QLabel('<font style="color: grey; background-color: yellow"><p>' + repr(name) + '</p></font>')
     label.move(QCursor.pos().x()+30,QCursor.pos().y()+20)
     label.setWindowFlags(QtCore.Qt.SplashScreen)
     label.show()
     QTimer.singleShot(10000,label.destroy)
Beispiel #13
0
 def __scaleBR(self):
     if (self.parent().width()==800 and QCursor.pos().x()<self.parent().x() and self.parent().height()==600 and QCursor.pos().y()<self.parent().y()):
         return
     else:
         if (self.parent().width()==800 and QCursor.pos().x()<self.parent().x()):
             self.__scaleBottom()
         elif (self.parent().height()==600 and QCursor.pos().y()<self.parent().y()):
             self.__scaleRight()
         else:
             self.parent().setGeometry(self.__lastGeo.x(), self.__lastGeo.y(), QCursor.pos().x()- self.__lastGeo.x(),   QCursor.pos().y()- self.__lastGeo.y())
             self.resized.emit()
Beispiel #14
0
 def recenter(self, pt=None, world=False):
     if pt is None:
         pt = self._mousePos
     ctr = self._transform.inverted()[0].map(self.rect().center())
     if not world:
         pt = self._transform.inverted()[0].map(pt)
     ctr -= pt
     self._transform.translate(ctr.x(), ctr.y())
     # move cursor to center of window
     QCursor.setPos(self.mapToGlobal(self.rect().center()))
     self.update()
Beispiel #15
0
 def eventFilter(self, viewport, ev):
     """Handles multiple events from the viewport.
     
     * update on View scroll
     * show the magnifier on left click+modifier
     
     """
     if ev.type() == QEvent.UpdateRequest:
         self.update()
     elif (not self.isVisible() and
           ev.type() == QEvent.MouseButtonPress and
           ev.modifiers() == self.showmodifier and
           ev.button() == self.showbutton):
         # show and drag while button pressed: DRAG_SHORT
         self._dragging = DRAG_SHORT
         self.moveCenter(ev.pos())
         self.show()
         viewport.setCursor(Qt.BlankCursor)
         return True
     elif self._dragging == DRAG_SHORT:
         if ev.type() == QEvent.MouseMove:
             if ev.buttons() == self.showbutton | self.resizebutton:
                 # DRAG_SHORT is busy, both buttons are pressed: resize!
                 if self._resizepos == None:
                     self._resizepos = ev.pos()
                     self._resizewidth = self.width()
                     dy = 0
                 else:
                     dy = (ev.pos() - self._resizepos).y()
                 g = self.geometry()
                 w = max(self.MIN_SIZE, self._resizewidth + 2 * dy)
                 self.resize(w, w)
                 self.moveCenter(g.center())
             else:
                 # just drag our center
                 self.moveCenter(ev.pos())
                 view = self.parent().parent()
                 view.scrollForDragging(ev.pos())
             return True
         elif ev.type() == QEvent.MouseButtonRelease:
             if ev.button() == self.showbutton:
                 # left button is released, stop dragging and/or resizing, hide
                 viewport.unsetCursor()
                 self.hide()
                 self._resizepos = None
                 self._dragging = False
                 view = self.parent().parent()
                 view.stopScrolling() # just if needed
             elif ev.button() == self.resizebutton:
                 # right button is released, stop resizing, warp cursor to center
                 self._resizepos = None
                 QCursor.setPos(viewport.mapToGlobal(self.geometry().center()))
             return True
     return False
Beispiel #16
0
 def __scaleTL(self):
     if (self.parent().width()==800 and QCursor.pos().x()>self.parent().x() and self.parent().height()==600 and QCursor.pos().y()>self.parent().y()):
         return
     else:
         if (self.parent().width()==800 and QCursor.pos().x()>self.parent().x()):
             self.__scaleTop()
         elif (self.parent().height()==600 and QCursor.pos().y()>self.parent().y()):
             self.__scaleLeft()
         else:
             self.parent().setGeometry(QCursor.pos().x(), QCursor.pos().y(), self.__lastGeo.x()-QCursor.pos().x()+self.__lastGeo.width(),  self.__lastGeo.height()-QCursor.pos().y()+self.__lastGeo.y())
             self.resized.emit()
Beispiel #17
0
 def showContextMenu(self):
     """Called when the user right-clicks or presses the context menu key."""
     pos = self.view.mapToGlobal(QPoint(0, 0))
     link, cursor = None, None
     # mouse inside view?
     if self.view.mapFromGlobal(QCursor.pos()) in self.view.viewport().rect():
         pos = QCursor.pos()
         pos_in_surface = self.view.surface().mapFromGlobal(pos)
         page, link = self.view.surface().pageLayout().linkAt(pos_in_surface)
         if link:
             cursor = self._links.cursor(link, True)
     self._contextMenu.show(pos, link, cursor)
Beispiel #18
0
    def on_click(self, event):
        """
        Callback for click on canvas.
        """
        _str = '{:s} click: button={:.0f}, x={:.0f}, y={:.0f}, xdata={}, ydata={}'.format(
            'double' if event.dblclick else 'single', event.button, event.x, event.y, event.xdata, event.ydata)
        self._ui.statusbar.showMessage(_str)

        # put up a pop up menu if right clicked on canvas
        if event.button == 3:
            from PyQt5.QtGui import QCursor
            cursor = QCursor()
            pos = cursor.pos()
            self._ui.popMenu.move(pos)
            self._ui.popMenu.show()
    def show_mode_menu(self):
        self.menu = Menu(play_sequence_sub_menu)
        self.menu.itemClicked.connect(self._menu_item_invoked)

        self.menu.getItemById("mode_group:radio:in_order").checked = \
            config.playerPlayOrderType == ORDER_TYPE_IN_ORDER
        self.menu.getItemById("mode_group:radio:random").checked = \
            config.playerPlayOrderType == ORDER_TYPE_RANDOM
        self.menu.getItemById("mode_group:radio:single").checked = \
            config.playerPlayOrderType == ORDER_TYPE_SINGLE
        self.menu.getItemById("mode_group:radio:single_cycle").checked = \
            config.playerPlayOrderType == ORDER_TYPE_SINGLE_CYCLE
        self.menu.getItemById("mode_group:radio:playlist_cycle").checked = \
            config.playerPlayOrderType == ORDER_TYPE_PLAYLIST_CYCLE

        self.menu.showRectMenu(QCursor.pos().x(), QCursor.pos().y())
    def timerEvent(self, event):
        """Handle events sent by the kinetic timer to decrease progressively
           the scrolling speed, eventually halting it.
        """
        count = 0
        if self._kineticData._state == KineticData.ManualScroll:
            count += 1
            cursorPos = QCursor.pos()
            self._kineticData._speed = cursorPos - self._kineticData._dragPos
            self._kineticData._dragPos = cursorPos    
        elif self._kineticData._state == KineticData.AutoScroll:
            count += 1
            p = self.scrollOffset()

            if self._kineticData._speed == QPoint(0, 0) or not self.setScrollOffset(p - self._kineticData._speed):
                self._kineticData._state = KineticData.Steady
                # reset speed to 0, as wheel scrolling accumulates speed instead of setting it to a fixed value.
                self._kineticData._speed = QPoint(0,0)
                # reset count to 0 to stop iterating.
                count = 0
                
            self._kineticData._speed = deaccelerate(self._kineticData._speed, 1, self._kineticData._maxSpeed)
    
        if count == 0:
            self._kineticData._ticker.stop()
            self.kineticScrollingActive.emit(False)
    
        super(KineticScrollArea, self).timerEvent(event)
Beispiel #21
0
    def node_context_menu(self, point):
        index = self.table_network.indexAt(point)
        model = self.table_network.model()
        if index.isValid() and index.row() < model.rowCount(QModelIndex()):
            source_index = model.mapToSource(index)
            is_root_col = model.sourceModel().columns_types.index('is_root')
            is_root_index = model.sourceModel().index(source_index.row(), is_root_col)
            is_root = model.sourceModel().data(is_root_index, Qt.DisplayRole)

            menu = QMenu()
            if is_root:
                unset_root = QAction(self.tr("Unset root node"), self)
                unset_root.triggered.connect(self.unset_root_node)
                unset_root.setData(self.community.network.root_node_index(source_index.row()))
                if len(self.community.network.root_nodes) > 1:
                    menu.addAction(unset_root)
            else:
                set_root = QAction(self.tr("Set as root node"), self)
                set_root.triggered.connect(self.set_root_node)
                set_root.setData(self.community.network.nodes[source_index.row()])
                menu.addAction(set_root)

            if self.app.preferences['expert_mode']:
                open_in_browser = QAction(self.tr("Open in browser"), self)
                open_in_browser.triggered.connect(self.open_node_in_browser)
                open_in_browser.setData(self.community.network.nodes[source_index.row()])
                menu.addAction(open_in_browser)

            # Show the context menu.
            menu.exec_(QCursor.pos())
Beispiel #22
0
 def updateCurrentColor(self):
     cursorPos = QCursor.pos()
     # Catch the pixel pointed by the mouse on a pixmap
     pixmap = QGuiApplication.screens()[self._desktop.screenNumber()].grabWindow(self._desktop.winId(), cursorPos.x(), cursorPos.y(), 1, 1)
     qImage = pixmap.toImage()
     qColor = QColor(qImage.pixel(0, 0))
     self.setCurrentColor(qColor)
Beispiel #23
0
def show(widget, pos=None, timeout=10000):
    """Show the widget at position."""
    if pos is None:
        pos = QCursor.pos()
    global _widget
    if _widget:
        if _widget is not widget:
            _widget.hide()
    else:
        global _handler
        if _handler is None:
            _handler = EventHandler()
        QApplication.instance().installEventFilter(_handler)
    
    # where to display the tooltip
    screen = QApplication.desktop().availableGeometry(pos)
    x = pos.x() + 2
    y = pos.y() + 20
    if x + widget.width() > screen.x() + screen.width():
        x -= 4 + widget.width()
    if y + widget.height() > screen.y() + screen.height():
        y -= 24 + widget.height()
    if y < screen.y():
        y = screen.y()
    if x < screen.x():
        x = screen.x()
    widget.move(x, y)
    if widget.windowFlags() & Qt.ToolTip != Qt.ToolTip:
        widget.setWindowFlags(Qt.ToolTip)
        widget.ensurePolished()
    
    widget.show()
    _widget = widget
    _timer.start(timeout)
    def zoom(self, factor, zoom_to_mouse_cursor=True, cursor_pos=None):
        if factor > 1 and self.view_rect().width() / factor < 300:
            factor = self.view_rect().width() / 300

        if zoom_to_mouse_cursor:
            pos = self.mapFromGlobal(QCursor.pos()) if cursor_pos is None else cursor_pos
        else:
            pos = None
        old_pos = self.mapToScene(pos) if pos is not None else None

        show_full = False
        if self.view_rect().width() / factor > self.sceneRect().width():
            self.show_full_scene()
            factor = 1
            show_full = True

        self.scale(factor, 1)
        if show_full:
            self.zoomed.emit(-1)
        else:
            self.zoomed.emit(factor)

        if pos is not None:
            move = self.mapToScene(pos) - old_pos
            self.translate(move.x(), 0)
Beispiel #25
0
 def __customContextMenuRequested(self, pos):
     """
     Private slot to handle the context menu request for the bookmarks tree.
     
     @param pos position the context menu was requested (QPoint)
     """
     from .BookmarkNode import BookmarkNode
     
     menu = QMenu()
     idx = self.bookmarksTree.indexAt(pos)
     idx = idx.sibling(idx.row(), 0)
     sourceIndex = self.__proxyModel.mapToSource(idx)
     node = self.__bookmarksModel.node(sourceIndex)
     if idx.isValid() and node.type() != BookmarkNode.Folder:
         menu.addAction(
             self.tr("&Open"), self.__openBookmarkInCurrentTab)
         menu.addAction(
             self.tr("Open in New &Tab"), self.__openBookmarkInNewTab)
         menu.addSeparator()
     act = menu.addAction(self.tr("Edit &Name"), self.__editName)
     act.setEnabled(idx.flags() & Qt.ItemIsEditable)
     if idx.isValid() and node.type() != BookmarkNode.Folder:
         menu.addAction(self.tr("Edit &Address"), self.__editAddress)
     menu.addSeparator()
     act = menu.addAction(
         self.tr("&Delete"), self.bookmarksTree.removeSelected)
     act.setEnabled(idx.flags() & Qt.ItemIsDragEnabled)
     menu.addSeparator()
     act = menu.addAction(self.tr("&Properties..."), self.__edit)
     act.setEnabled(idx.flags() & Qt.ItemIsEditable)
     menu.exec_(QCursor.pos())
    def nextFrame(self):
        mouse_pos = self.mapFromGlobal(QCursor.pos())
        mouse_x = mouse_pos.x()
        mouse_y = mouse_pos.y()

        self.x1 = mouse_x
        self.y1 = mouse_y
        self.radius1 = self.radius1 + math.sin(self.frame_count / 8) * 4

        delay = 20
        self.x2 += (mouse_x - self.x2) / delay
        self.y2 += (mouse_y - self.y2) / delay

        self.frame_count += 1

        if self.paint_image.width() != self.width() or self.paint_image.height() != self.height():
            self.paint_image = QPixmap(self.width(), self.height())
            self.paint_image.fill(self.background_color)

        p = QPainter()
        p.begin(self.paint_image) # auf das paint_image malen
        p.setBackground(self.background_color) # color when stuff is erased

        # Hintergrund löschen, wenn Rechteck bei der Maus angekommen ist
        # print("{0}, {1}".format(self.x2, mouse_x))
        if round(self.x2) == mouse_x and round(self.y2) == mouse_y:
            p.eraseRect(0, 0, self.paint_image.width(), self.paint_image.height())

        self.drawFrame(p)
        p.end()
        self.repaint()
Beispiel #27
0
    def right_click(self, type, champ):
        "Retourne une fonction qui sera executée lors d'un clic droit sur le champ 'champ'."
        champ.setFocus()
        plusieurs = isinstance(type, list)
        if plusieurs:
            type = type[0]
        liste_objets = self.onglet_actuel.feuille_actuelle.objets.lister(False, type = type)
        liste_objets.sort(key = attrgetter('nom')) # ordre alphabétique
        if not liste_objets:
            return
        menu = QMenu()

        for obj in liste_objets:
            action = menu.addAction(obj.nom_complet)
            action.nom = obj.nom

        action = menu.exec_(QCursor.pos())
        if action:
            if plusieurs:
                # le champ doit contenir non pas un objet, mais une liste d'objets
                val = champ.text().strip()
                if val:
                    if not val.endswith(","):
                        val += ","
                    val += " "
                champ.setText(val + action.nom)
            else:
                # le champ contient un seul objet
                champ.setText(action.nom)
Beispiel #28
0
 def __showContextMenu(self):
     """
     Private slot to show the context menu.
     """
     menu = QMenu()
     act = menu.addAction(self.tr("Object blocked by ClickToFlash"))
     font = act.font()
     font.setBold(True)
     act.setFont(font)
     menu.addAction(
         self.tr("Show information about object"), self.__showInfo)
     menu.addSeparator()
     menu.addAction(self.tr("Load"), self.__load)
     menu.addAction(self.tr("Delete object"), self.__hideAdBlocked)
     menu.addSeparator()
     host = self.__url.host()
     add = menu.addAction(
         self.tr("Add '{0}' to Whitelist").format(host),
         self.__addToWhitelist)
     remove = menu.addAction(
         self.tr("Remove '{0}' from Whitelist").format(host),
         self.__removeFromWhitelist)
     onWhitelist = self.__plugin.onWhitelist(host)
     add.setEnabled(not onWhitelist)
     remove.setEnabled(onWhitelist)
     menu.addSeparator()
     menu.addAction(self.tr("Configure Whitelist"), self.__configure)
     menu.actions()[0].setEnabled(False)
     
     menu.exec_(QCursor.pos())
Beispiel #29
0
  def __init__(self):

    QLabel.__init__(self)

    self.setWindowFlags(self.windowFlags() | Qt.FramelessWindowHint)
    self.setAttribute(Qt.WA_NoSystemBackground)
    self.setMouseTracking(True)

    self.dragPosition  = QPoint(0, 0)
    self.mousePosition = QCursor.pos()

    self.actionFaces = QActionGroup(self)
    allFaceActions   = []

    for name in sorted(self.faces):

      action = QAction(name, self.actionFaces)
      action.setCheckable(True)
      allFaceActions.append(action)

    self.actionFaces.triggered.connect(self.actionUpdateFace)

    startAction = random.choice(allFaceActions)
    startAction.setChecked(True)
    self.actionUpdateFace(startAction)

    self.actionQuit = QAction("Quit", self)
    self.actionQuit.triggered.connect(QApplication.instance().quit)

    self.timer = QTimer()
    self.timer.timeout.connect(self.updateFromMousePosition)

    self.timer.start(self.update_interval)

    self.painter = None
Beispiel #30
0
 def verifier_feuille(self, eq1, eq2):
     print(eq1, eq2)
     for nom, eq in (('d1', eq1), ('d2', eq2)):
         if nom in self.feuille_actuelle.objets.noms:
             d = self.feuille_actuelle.objets[nom]
             d.label(mode='nom')
             champ = self.feuille_actuelle.objets['champ_cache_' + nom]
             M, N = d
             M = (int(M.x), int(M.y))
             N = (int(N.x), int(N.y))
             if self.eq_reduite(M, N) == eq:
                 d.style(couleur='g')
                 champ.texte = 'ok'
                 msg = 'La droite %s est correcte.' % nom
                 if nom == 'd1':
                     msg += ' Construisez maintenant d2.'
             else:
                 print(self.eq_reduite(*d), eq)
                 d.style(couleur='r')
                 # On peut mettre n'importe quoi différent de ok dans
                 # champ, l'idée étant que si la droite est fausse mais
                 # n'a pas changé, on ne perde pas de point, et par
                 # contre on perde des points en cas de changement si
                 # c'est toujours faux.
                 champ.texte = str(d.equation)
                 msg = "Attention, la droite %s est fausse." % nom
             QToolTip.showText(QCursor.pos(), msg)
             self.canvas.message(msg, temporaire=False)
Beispiel #31
0
 def _on_add_item_clicked(self):
     self.new_menu.exec_(QCursor.pos())
Beispiel #32
0
 def contextMenuEvent(self, event):
     self.popMenu.popup(QCursor.pos())
Beispiel #33
0
    def setupReadOnly(self, loadcp=True):
        self.closeButton.setVisible(True)
        self.Cutplans.AddButton.setVisible(False)
        qry = "SELECT * FROM simulation.fullresults Where SimID = " + str(
            self.simid)
        data = read_sql(qry, self.db)
        self.nameTextbox.setText(data["SimName"][0])
        self.nameTextbox.setDisabled(True)
        qry = "SELECT CutplanID as ID, NumLogs as \"Log Count\" From " + \
              "cutplans WHERE SimID = " + str(self.simid)

        self.results = data.iloc[:, 3:15].copy()
        self.results.columns = [
            'RunTime', 'LogsCut', 'Production', 'LogVolume', 'Recovery',
            'LogRate', 'Uptime', 'MSLDT', 'BSLDT', 'TSLDT', 'Sawdust', 'Shift'
        ]
        self.results.loc[self.results.index[0],
                         'Shift'] = self.results.shape[0]
        self.results = self.results.sort_values(by=['Shift'])
        self.results['Sawdust'] = self.results['Sawdust'] / \
            self.results['LogVolume']
        self.ResultsWidget.updateResults(self.results)

        if loadcp:
            cpdata = read_sql(qry, self.db)
            self.Cutplans.AddCP(addData=cpdata, errors=self.CheckCPErrors())

        qry = "SELECT * From SimHistory Where SimID = " + str(self.simid) + ";"
        settings = read_sql(qry, self.db)
        self.loggap_setting = settings.LogGap[0]
        dt = settings.Downtime[0]
        if dt == 0:
            self.downtime_setting = []
            for i in range(len(self.SettingsUI.downtimeCBs)):
                self.downtime_setting.append(False)
        elif dt == 1:
            self.downtime_setting = []
            for i in range(len(self.SettingsUI.downtimeCBs)):
                self.downtime_setting.append(True)
        else:
            qry = "SELECT * FROM DowntimeSettings Where SimID = " + str(
                self.simid) + ";"
            dt = read_sql(qry, self.db)
            for i in range(len(self.SettingsUI.downtimeCBs)):
                x = (dt.iloc[0, i + 1] == 1)
                self.SettingsUI.downtimeCBs[i].setChecked(x)
        self.SettingsUI.numbinsTB.setValue(settings.NumBins[0])
        if settings.LineSpeed[0] == 55.0:
            self.SettingsUI.highspeedRB.setChecked(True)
        elif settings.LineSpeed[0] == 35.0:
            self.SettingsUI.lowspeedRB.setChecked(True)
        elif settings.LineSpeed[0] == -1.0:
            self.SettingsUI.autospeedRB.setChecked(True)
        else:
            self.SettingsUI.customspeedRB.setChecked(True)
            self.SettingsUI.customspeedTB.setValue(settings.LineSpeed[0])
        if settings.Downtime[0] == 0:
            qry = "SELECT * FROM CutbackSettings Where SimID = " + str(
                self.simid) + ";"
            cb = read_sql(qry, self.db)
            for i in range(len(self.SettingsUI.downtimeCBs)):
                x = (cb.iloc[0, i + 1] == 1)
                self.SettingsUI.downtimeCBs[i].setChecked(x)

        self.SettingsUI.buttonbox.setStandardButtons(QDialogButtonBox.Cancel)
        for w in self.SettingsUI.buttonbox.children():
            if w.metaObject().className() == "QPushButton":
                w.setCursor(QCursor(Qt.PointingHandCursor))
        self.SettingsUI.setupReadOnly()
Beispiel #34
0
    def FillPhotosByFilter(self, filter):

        # it's tempting to think that we could use the insertPhotoIntoTable routine,
        # but we can't here, because if we're filling photos by filter, we already know
        # each photo's meta data.  The insertPhotoIntoTable routine tries to guess the
        # location, time, species, etc. from the photo file's embedded meta data.

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        self.scaleMe()
        self.resizeMe()

        self.fillingCombos = True

        # save the filter settings passed to this routine to the form itself for future use
        self.filter = filter

        photoSightings = self.mdiParent.db.GetSightingsWithPhotos(filter)

        if len(photoSightings) == 0:
            return False

        row = 0

        # count photos for message display
        photoCount = 0
        for s in photoSightings:
            photoCount = photoCount + len(s["photos"])
        photoCount = str(photoCount)

        for s in photoSightings:
            for p in s["photos"]:

                self.mdiParent.lblStatusBarMessage.setVisible(True)
                self.mdiParent.lblStatusBarMessage.setText(
                    "Processing photo " + str(row + 1) + " of " + photoCount)

                # p is a filename. Use it to add the image to the label as a pixmap
                buttonPhoto = QPushButton()
                buttonPhoto.setMinimumHeight(281)
                buttonPhoto.setMinimumWidth(500)

                # get thumbnail from file to display
                pixMap = self.GetPixmapForThumbnail(p["fileName"])

                buttonPhoto.setIcon(QIcon(pixMap))

                # size to 500x281
                buttonPhoto.setIconSize(QSize(500, 281))
                buttonPhoto.setStyleSheet(
                    "QPushButton {background-color: #343333; border: 0px}")

                # display thumbnail to new row in grid
                self.gridPhotos.addWidget(buttonPhoto, row, 0)

                # set up layout in second column of row to house combo boxes
                # give each object a name according to the row so we can access them later
                container = QWidget()
                container.setObjectName("container" + str(row))
                detailsLayout = QVBoxLayout(container)
                detailsLayout.setObjectName("layout" + str(row))
                detailsLayout.setAlignment(Qt.AlignTop)
                self.gridPhotos.addWidget(container, row, 1)

                # create combo boxes for details
                # add connection for when user changes a combo box
                cboLocation = QComboBox()
                cboLocation.currentIndexChanged.connect(
                    partial(self.cboLocationChanged, row))

                cboDate = QComboBox()
                cboDate.currentIndexChanged.connect(
                    partial(self.cboDateChanged, row))

                cboTime = QComboBox()
                cboTime.currentIndexChanged.connect(
                    partial(self.cboTimeChanged, row))

                cboCommonName = QComboBox()
                cboCommonName.currentIndexChanged.connect(
                    partial(self.cboCommonNameChanged, row))

                cboRating = QComboBox()
                cboRating.addItems(["Not Rated", "1", "2", "3", "4", "5"])
                cboRating.currentIndexChanged.connect(
                    partial(self.cboRatingChanged, row))

                # set stylesheet for cmbo boxes
                for c in [
                        cboLocation, cboDate, cboTime, cboCommonName, cboRating
                ]:
                    self.removeHighlight(c)

                # fill location combo box with all locations in db
                locations = self.mdiParent.db.locationList
                cboLocation.addItems(locations)

                # set location combo box to the photo's location
                index = cboLocation.findText(s["location"])
                if index >= 0:
                    cboLocation.setCurrentIndex(index)

                # fill date combo box with all dates associated with selected location
                filterForThisPhoto = code_Filter.Filter()
                filterForThisPhoto.setLocationName(s["location"])
                filterForThisPhoto.setLocationType("Location")
                dates = self.mdiParent.db.GetDates(filterForThisPhoto)
                cboDate.addItems(dates)

                # set date  combo box to the photo's associated date
                index = cboDate.findText(s["date"])
                if index >= 0:
                    cboDate.setCurrentIndex(index)

                # fill time combo box with all times associated with selected location and date
                filterForThisPhoto.setStartDate(s["date"])
                filterForThisPhoto.setEndDate(s["date"])
                startTimes = self.mdiParent.db.GetStartTimes(
                    filterForThisPhoto)
                cboTime.addItems(startTimes)

                # set time combo box to the photo's associated checklist time
                index = cboTime.findText(s["time"])
                if index >= 0:
                    cboTime.setCurrentIndex(index)

                # get common names from checklist associated with photo
                filterForThisPhoto.setChecklistID(s["checklistID"])
                commonNames = self.mdiParent.db.GetSpecies(filterForThisPhoto)

                cboCommonName.addItem("**Detach Photo**")
                cboCommonName.addItems(commonNames)

                # set combo box to common name
                index = cboCommonName.findText(s["commonName"])
                if index >= 0:
                    cboCommonName.setCurrentIndex(index)

                # set combo box to rating value
                index = int(p["rating"])
                cboRating.setCurrentIndex(index)

                # assign names to combo boxes for future access
                cboLocation.setObjectName("cboLocation" + str(row))
                cboDate.setObjectName("cboDate" + str(row))
                cboTime.setObjectName("cboTime" + str(row))
                cboCommonName.setObjectName("cboCommonName" + str(row))
                cboRating.setObjectName("cboRating" + str(row))

                # add combo boxes to the layout in second column
                detailsLayout.addWidget(cboLocation)
                detailsLayout.addWidget(cboDate)
                detailsLayout.addWidget(cboTime)
                detailsLayout.addWidget(cboCommonName)
                detailsLayout.addWidget(cboRating)

                # create and add resent button
                btnReset = QPushButton()
                btnReset.setText("Reset")
                btnReset.clicked.connect(partial(self.btnResetClicked, row))
                detailsLayout.addWidget(btnReset)

                # save meta data for future use when user clicks cbo boxes
                thisPhotoMetaData = {}
                thisPhotoMetaData["photoFileName"] = p["fileName"]
                thisPhotoMetaData["location"] = s["location"]
                thisPhotoMetaData["date"] = s["date"]
                thisPhotoMetaData["time"] = s["time"]
                thisPhotoMetaData["commonName"] = s["commonName"]
                thisPhotoMetaData["photoData"] = p
                thisPhotoMetaData["rating"] = p["rating"]

                self.metaDataByRow[row] = thisPhotoMetaData

                # initialize the "new" data so that there are values there, even if they're not really new
                # user can change the cbo boxes later, which will also change the "new" data
                self.saveNewMetaData(row)

                row = row + 1

                qApp.processEvents()

        self.mdiParent.lblStatusBarMessage.setText("")
        self.mdiParent.lblStatusBarMessage.setVisible(False)

        QApplication.processEvents()

        icon = QIcon()
        icon.addPixmap(QPixmap(":/icon_camera.png"), QIcon.Normal, QIcon.Off)
        self.setWindowIcon(icon)
        self.setWindowTitle("Manage Photos")

        self.fillingCombos = False

        QApplication.restoreOverrideCursor()

        # tell MainWindow that we succeeded filling the list
        return (True)
Beispiel #35
0
 def open_manga_context_menu(self):
     self.manga_selected(self.mangas_list.currentRow()),
     self.manga_context_menu.exec_(QCursor.pos())
Beispiel #36
0
 def on_copy(self):
     self.app.clipboard().setText(self.text())
     QToolTip.showText(QCursor.pos(), _("Text copied to clipboard"), self)
Beispiel #37
0
	def moveToolWindows ( self, toolWindows, area ):
		if type ( area ) == int:
			area = AreaReference ( area )

		for toolWindow in toolWindows:
			if not self.hasToolWindow ( toolWindow ): return
			if toolWindow.parentWidget ():
				self.releaseToolWindow ( toolWindow )

		areaType = area.type

		if areaType == ToolWindowManager.LastUsedArea and not self.lastUsedArea:
			foundArea = self.findChild ( ToolWindowManagerArea )
			if foundArea:
				area = AreaReference ( ToolWindowManager.AddTo, foundArea )
			else:
				area = ToolWindowManager.EmptySpace

		if areaType == ToolWindowManager.NoArea:
			#do nothing
			# qWarning ( '[moveToolWindows] areaType = NoArea' )
			pass

		elif areaType == ToolWindowManager.NewFloatingArea:
			area = self.createArea ()
			area.addToolWindows ( toolWindows )
			wrapper = ToolWindowManagerWrapper ( self )
			wrapper.layout ().addWidget ( area )
			wrapper.move ( QCursor.pos () )
			wrapper.show ()

			# qWarning ( '[moveToolWindows] areaType = NewFloatingArea' )

		elif areaType == ToolWindowManager.AddTo:
			area.area ().addToolWindows ( toolWindows )

			# qWarning ( '[moveToolWindows] areaType = AddTo' )

		elif areaType in ( ToolWindowManager.LeftOf, ToolWindowManager.RightOf, ToolWindowManager.TopOf, ToolWindowManager.BottomOf ):
			parentSplitter = cast ( area.widget.parentWidget (), QSplitter )
			wrapper = cast ( area.widget.parentWidget (), ToolWindowManagerWrapper )
			if not ( parentSplitter or wrapper ):
				qWarning ( 'unknown parent type' )
				return
			# import pudb; pu.db
			useParentSplitter = False
			indexInParentSplitter = 0
			if parentSplitter:
				indexInParentSplitter = parentSplitter.indexOf ( area.widget )
				if parentSplitter.orientation () == Qt.Vertical:
					useParentSplitter = areaType in ( ToolWindowManager.TopOf, ToolWindowManager.BottomOf )
				else:
					useParentSplitter = areaType in ( ToolWindowManager.LeftOf, ToolWindowManager.RightOf )

			if useParentSplitter:
				if areaType in ( ToolWindowManager.BottomOf , ToolWindowManager.RightOf ):
					indexInParentSplitter += 1
				newArea = self.createArea ()
				newArea.addToolWindows ( toolWindows )
				parentSplitter.insertWidget ( indexInParentSplitter, newArea )

			else:
				area.widget.hide ()
				area.widget.setParent ( None )
				splitter = self.createSplitter ()
				if areaType in ( ToolWindowManager.TopOf, ToolWindowManager.BottomOf ):
					splitter.setOrientation (Qt.Vertical)
				else:
					splitter.setOrientation (Qt.Horizontal)

				splitter.addWidget ( area.widget )
				area.widget.show ()
				newArea = self.createArea ()
				if areaType in ( ToolWindowManager.TopOf, ToolWindowManager.LeftOf ):
					splitter.insertWidget ( 0, newArea )
				else:
					splitter.addWidget ( newArea )

				if parentSplitter:
					parentSplitter.insertWidget ( indexInParentSplitter, splitter )
				else:
					wrapper.layout ().addWidget ( splitter )
				newArea.addToolWindows ( toolWindows )

			# qWarning ( '[moveToolWindows] areaType = LeftOf/RightOf/TopOf/BottomOf' )

		elif areaType == ToolWindowManager.EmptySpace:
			wrapper = self.findChild ( ToolWindowManagerWrapper )
			if wrapper.isOccupied ():
				self.lastUsedArea.addToolWindows ( toolWindows )
			else:
				newArea = self.createArea ()
				wrapper.layout ().addWidget ( newArea )
				newArea.addToolWindows ( toolWindows )

			# qWarning ( '[moveToolWindows] areaType = EmptySpace' )

		elif areaType == ToolWindowManager.LastUsedArea:
			self.lastUsedArea.addToolWindows ( toolWindows )

			# qWarning ( '[moveToolWindows] areaType = areaType == ToolWindowManager.LastUsedArea' )

		else:
			qWarning ( 'invalid type' )

		self.simplifyLayout ()
		for toolWindow in toolWindows:
			self.toolWindowVisibilityChanged.emit ( toolWindow, toolWindow.parent () != None )
Beispiel #38
0
 def mousePressEvent(self, event):
     if event.button() == Qt.LeftButton:
         self.m_flag = True
         self.m_Position = event.globalPos() - self.pos()  # 获取鼠标相对窗口的位置
         event.accept()
         self.setCursor(QCursor(Qt.OpenHandCursor))  # 更改鼠标图标
Beispiel #39
0
 def link_to_window(self, toggle_func: Callable[[], None]) -> None:
     self.mouseReleaseEvent = toggle_func
     self.enterEvent = lambda x: app_state.app.setOverrideCursor(
         QCursor(Qt.PointingHandCursor))
     self.leaveEvent = lambda x: app_state.app.setOverrideCursor(
         QCursor(Qt.ArrowCursor))
Beispiel #40
0
 def mousePressEvent(self, event):
     if event.button() == Qt.LeftButton:
         self.is_move = True
         self.move_xy = event.globalPos() - self.pos()  # 获取鼠标的移动事件
         # self.parent_rect = self.parent().pos()
         self.setCursor(QCursor(Qt.OpenHandCursor))  # 设置鼠标为抓手
Beispiel #41
0
 def open_chapter_context_menu(self):
     self.chapter_context_menu.exec_(QCursor.pos())
 def update_inspection(self):
     widget = qApp.widgetAt(QCursor.pos())
     self.update_selected_widget(widget)
Beispiel #43
0
 def pop_up(self, move=True):
     if move:
         self.move(QCursor.pos())
     return self.confirmFlag if self.exec() else None
Beispiel #44
0
 def mouseReleaseEvent(self, QMouseEvent):
     '''
     Mevcut fare bırakma olaylarını yeniden tanımlayın
     '''
     self.m_flag = False
     self.setCursor(QCursor(Qt.ArrowCursor))
Beispiel #45
0
 def mouseReleaseEvent(self, event):
     self.is_move = False
     self.setCursor(QCursor(Qt.ArrowCursor))  # 设置鼠标为正常
    def initialize_views(self):
        """
        初始化
        :return:
        """
        # 标题图标标签
        self.iconLabel = QLabel(self)
        self.iconLabel.setObjectName('iconLabel')
        # 标题标签
        self.titleLabel = QLabel(self)
        self.titleLabel.setObjectName('titleLabel')
        # 最小化按钮
        self.minButton = QPushButton(self)
        self.minButton.setObjectName('titleBarButton')
        self.minButton.setIconSize(QSize(30, 30))

        # 复原按钮
        self.restoreButton = QPushButton(self)
        self.restoreButton.setObjectName('titleBarButton')
        self.restoreButton.setIconSize(
            QSize(Const.ICON_WIDTH, Const.ICON_HEIGHT))
        # 最大化按钮
        self.maxButton = QPushButton(self)
        self.maxButton.setObjectName("titleBarButton")
        self.maxButton.setIconSize(QSize(Const.ICON_WIDTH, Const.ICON_HEIGHT))
        # 关闭按钮
        self.closeButton = QPushButton(self)
        self.closeButton.setObjectName('titleBarButton')
        self.closeButton.setIconSize(QSize(Const.ICON_WIDTH,
                                           Const.ICON_HEIGHT))
        # 设置大小
        self.minButton.setFixedSize(Const.TITLE_BUTTON_SIZE,
                                    Const.TITLE_BUTTON_SIZE)
        self.restoreButton.setFixedSize(Const.TITLE_BUTTON_SIZE,
                                        Const.TITLE_BUTTON_SIZE)
        self.maxButton.setFixedSize(Const.TITLE_BUTTON_SIZE,
                                    Const.TITLE_BUTTON_SIZE)
        self.closeButton.setFixedSize(Const.TITLE_BUTTON_SIZE,
                                      Const.TITLE_BUTTON_SIZE)

        self.iconLabel.setAlignment(Qt.AlignLeft)
        self.titleLabel.setAlignment(Qt.AlignLeft)

        # 设置图标
        self.minButton.setIcon(QIcon(Const.TITLE_MIN_ICON))
        self.restoreButton.setIcon(QIcon(Const.TITLE_RESTORE_ICON))
        self.closeButton.setIcon(QIcon(Const.TITLE_CLOSE_ICON))

        # 设置提示信息
        self.iconLabel.setToolTip('标题图标')
        self.minButton.setToolTip('最小化')
        self.restoreButton.setToolTip('复原')
        self.closeButton.setToolTip('关闭')

        # 设置鼠标手势
        self.minButton.setCursor(QCursor(Qt.PointingHandCursor))
        self.restoreButton.setCursor(QCursor(Qt.PointingHandCursor))
        self.closeButton.setCursor(QCursor(Qt.PointingHandCursor))

        # 水平布局
        self.allLayout = QHBoxLayout(self)
        self.allLayout.setObjectName('allLayout')
        self.setLayout(self.allLayout)

        self.allLayout.setSpacing(Const.SPACING)  # 去除控件之间的距离
        self.allLayout.setContentsMargins(Const.MARGINS, Const.MARGINS,
                                          Const.MARGINS, Const.MARGINS)

        # 往布局里添加控件
        self.allLayout.addWidget(self.iconLabel)
        self.allLayout.addWidget(self.titleLabel)
        self.allLayout.addWidget(self.minButton)
        self.allLayout.addWidget(self.restoreButton)
        self.allLayout.addWidget(self.maxButton)
        self.allLayout.addWidget(self.closeButton)
Beispiel #47
0
 def __init__(self, parent=None):
     super(MainWindow, self).__init__()
     self.statusBar().showMessage("Move Dial to Deform Microphone Voice !.")
     self.setWindowTitle(__doc__)
     self.setMinimumSize(240, 240)
     self.setMaximumSize(480, 480)
     self.resize(self.minimumSize())
     self.setWindowIcon(QIcon.fromTheme("audio-input-microphone"))
     self.tray = QSystemTrayIcon(self)
     self.center()
     QShortcut("Ctrl+q", self, activated=lambda: self.close())
     self.menuBar().addMenu("&File").addAction("Quit", lambda: exit())
     self.menuBar().addMenu("Sound").addAction(
         "STOP !", lambda: call('killall rec', shell=True))
     windowMenu = self.menuBar().addMenu("&Window")
     windowMenu.addAction("Hide", lambda: self.hide())
     windowMenu.addAction("Minimize", lambda: self.showMinimized())
     windowMenu.addAction("Maximize", lambda: self.showMaximized())
     windowMenu.addAction("Restore", lambda: self.showNormal())
     windowMenu.addAction("FullScreen", lambda: self.showFullScreen())
     windowMenu.addAction("Center", lambda: self.center())
     windowMenu.addAction("Top-Left", lambda: self.move(0, 0))
     windowMenu.addAction("To Mouse", lambda: self.move_to_mouse_position())
     # widgets
     group0 = QGroupBox("Voice Deformation")
     self.setCentralWidget(group0)
     self.process = QProcess(self)
     self.process.error.connect(
         lambda: self.statusBar().showMessage("Info: Process Killed", 5000))
     self.control = QDial()
     self.control.setRange(-10, 20)
     self.control.setSingleStep(5)
     self.control.setValue(0)
     self.control.setCursor(QCursor(Qt.OpenHandCursor))
     self.control.sliderPressed.connect(
         lambda: self.control.setCursor(QCursor(Qt.ClosedHandCursor)))
     self.control.sliderReleased.connect(
         lambda: self.control.setCursor(QCursor(Qt.OpenHandCursor)))
     self.control.valueChanged.connect(
         lambda: self.control.setToolTip(f"<b>{self.control.value()}"))
     self.control.valueChanged.connect(lambda: self.statusBar().showMessage(
         f"Voice deformation: {self.control.value()}", 5000))
     self.control.valueChanged.connect(self.run)
     self.control.valueChanged.connect(lambda: self.process.kill())
     # Graphic effect
     self.glow = QGraphicsDropShadowEffect(self)
     self.glow.setOffset(0)
     self.glow.setBlurRadius(99)
     self.glow.setColor(QColor(99, 255, 255))
     self.control.setGraphicsEffect(self.glow)
     self.glow.setEnabled(False)
     # Timer to start
     self.slider_timer = QTimer(self)
     self.slider_timer.setSingleShot(True)
     self.slider_timer.timeout.connect(self.on_slider_timer_timeout)
     # an icon and set focus
     QLabel(self.control).setPixmap(
         QIcon.fromTheme("audio-input-microphone").pixmap(32))
     self.control.setFocus()
     QVBoxLayout(group0).addWidget(self.control)
     self.menu = QMenu(__doc__)
     self.menu.addAction(__doc__).setDisabled(True)
     self.menu.setIcon(self.windowIcon())
     self.menu.addSeparator()
     self.menu.addAction(
         "Show / Hide", lambda: self.hide()
         if self.isVisible() else self.showNormal())
     self.menu.addAction("STOP !", lambda: call('killall rec', shell=True))
     self.menu.addSeparator()
     self.menu.addAction("Quit", lambda: exit())
     self.tray.setContextMenu(self.menu)
     self.make_trayicon()
Beispiel #48
0
    def mainloop(self):
        # サイズ更新
        sgm = getScreenGeomtry()
        if sgm != self.targetScreenGeometry:
            self.dpWindow.setGeometry(sgm)
            self.canvas.setCanvas(sgm.size())
            self.dpMenu.setPositionPercent(self.dpMenu.myPositionPercent[0],
                                           self.dpMenu.myPositionPercent[1])
            self.targetScreenGeometry = sgm

        # キー情報 actionKey[0] - 押しているか?   actionKey[1] - 直後か?
        if self.actionKey[1] == True:
            self.actionKey = (self.actionKey[0], False)
        if (is_pressed("ctrl") and not self.actionKey[0]):
            self.actionKey = (True, True)
        elif (not is_pressed("ctrl") and self.actionKey[0]):
            self.actionKey = (False, True)

        # 表示扱いで非表示なら表示 または 逆
        if self.isVisible and not self.dpWindow.isVisible():
            self.dpWindow.show()
        elif not self.isVisible and self.dpWindow.isVisible():
            self.dpWindow.hide()

        # dplabel更新
        self.dpMenu.getFocusLabel()
        flp = self.dpMenu.prevFocusLabel
        if flp[0] != flp[1]:
            if flp[0] != 0:
                flp[0].changeStyleSheet("background-color",
                                        "rgba(0,100,100,100)")
            if flp[1] != 0:
                flp[1].changeStyleSheet("background-color", "rgba(0,0,0,50)")

        if self.actionKey == (True, True):  # キーを押したとき
            if flp[0] != 0:
                None
            else:
                None

            self.pushedLabel = flp[0]
        elif self.actionKey == (False, True):  # キーを離したとき
            if flp[0] != 0:  # dpLabelなら
                if self.pushedLabel == self.dpMenu.labelList[0] and flp[
                        0] == self.dpMenu.labelList[0]:
                    self.dpMenu.togleLayout()
                if self.pushedLabel == self.dpMenu.labelList[1] and flp[
                        0] == self.dpMenu.labelList[1]:
                    sys.exit()
                if self.pushedLabel == self.dpMenu.labelList[2] and flp[
                        0] == self.dpMenu.labelList[2]:
                    if not self.isPenActive:
                        self.isPenActive = not self.isPenActive
                        flp[0].changeStyleSheet("color", "rgba(255,255,0,200)")
                    else:
                        self.isPenActive = not self.isPenActive
                        flp[0].changeStyleSheet("color",
                                                "rgba(255,255,255,200)")
                if self.pushedLabel == self.dpMenu.labelList[3] and flp[
                        0] == self.dpMenu.labelList[3]:
                    color = QColorDialog().getColor(self.penColor,
                                                    self.dpWindow, "色を選択")
                    self.penColor = color
                    flp[0].changeStyleSheet(
                        "color",
                        f"rgb({color.red()},{color.green()},{color.blue()})")
                if self.pushedLabel == self.dpMenu.labelList[4] and flp[
                        0] == self.dpMenu.labelList[4]:
                    self.canvas.setCanvas(self.dpWindow.size())
            else:  #label以外
                if self.pushedLabel == self.dpMenu.labelList[0]:
                    pos = self.dpWindow.mapFromGlobal(QCursor.pos())
                    xp = int(100 * pos.x() / self.dpWindow.width())
                    yp = int(100 * pos.y() / self.dpWindow.height())
                    self.dpMenu.setPositionPercent(xp, yp)

            self.pushedLabel = 0

        if self.actionKey[0] == True:
            if flp[0] != 0:
                None
            else:
                if self.canvas.isCursorOnMe() and self.isPenActive:
                    self.canvas.drawLine(
                        self.canvas.mapFromGlobal(self.prevCursorPos),
                        self.canvas.mapFromGlobal(QCursor().pos()), 5,
                        self.penColor)

        # cursorバッファ更新
        self.prevCursorPos = QCursor().pos()

        # ループ用タイマー
        self.dpTimer.start()
Beispiel #49
0
 def leaveEvent(self, event):
     self.font.setUnderline(False)
     self.setFont(self.font)
     self.app.setOverrideCursor(QCursor(Qt.ArrowCursor))
     return QLabel.leaveEvent(self, event)
Beispiel #50
0
    def __init__(self, parent=None):
        super(Ui_Item, self).__init__(parent)
        sizePolicy = QtWidgets.QSizePolicy(
            QtWidgets.QSizePolicy.MinimumExpanding,
            QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        self.setMaximumSize(QtCore.QSize(16777215, 260))
        self.setStyleSheet("QWidget {\n"
                           "    background: transparent;\n"
                           "}\n"
                           "\n"
                           "* {\n"
                           "    color: #ffffff;\n"
                           "}\n"
                           "\n"
                           "#widget,#widget_2 {\n"
                           "    border: 1px solid #121212;\n"
                           "    border-radius: 10px;\n"
                           "    background-color: #12000000;\n"
                           "}\n"
                           "\n"
                           "#title,#title2 {\n"
                           "    color: #E65100;\n"
                           "    font-weight: bold;\n"
                           "}")
        self.verticalLayout = QtWidgets.QVBoxLayout(self)
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setSizeConstraint(
            QtWidgets.QLayout.SetNoConstraint)
        self.horizontalLayout.setSpacing(0)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.widget_2 = QtWidgets.QWidget(self)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
                                           QtWidgets.QSizePolicy.Maximum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.widget_2.sizePolicy().hasHeightForWidth())
        self.widget_2.setSizePolicy(sizePolicy)
        self.widget_2.setMaximumSize(QtCore.QSize(16777215, 240))
        self.widget_2.setObjectName("widget_2")
        self.horizontalLayout_6 = QtWidgets.QHBoxLayout(self.widget_2)
        self.horizontalLayout_6.setSizeConstraint(
            QtWidgets.QLayout.SetDefaultConstraint)
        self.horizontalLayout_6.setObjectName("horizontalLayout_6")
        self.label = QtWidgets.QLabel(self.widget_2)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum,
                                           QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.label.sizePolicy().hasHeightForWidth())
        self.label.setSizePolicy(sizePolicy)
        self.label.setMaximumSize(QtCore.QSize(250, 16777215))
        self.label.setText("")
        self.label.setTextFormat(QtCore.Qt.RichText)
        self.label.setScaledContents(False)
        self.label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignTop)
        self.label.setObjectName("label")
        self.label.hide()
        self.label.setCursor(QCursor(Qt.PointingHandCursor))

        self.label.mousePressEvent = partial(self._downloadImage)

        self.horizontalLayout_6.addWidget(self.label)
        self.verticalLayout_3 = QtWidgets.QVBoxLayout()
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.horizontalLayout_5 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_5.setObjectName("horizontalLayout_5")
        spacerItem = QtWidgets.QSpacerItem(8, 20, QtWidgets.QSizePolicy.Fixed,
                                           QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_5.addItem(spacerItem)
        self.title2 = QtWidgets.QLabel(self.widget_2)
        self.title2.setObjectName("title2")
        self.horizontalLayout_5.addWidget(self.title2)
        self.label_2 = QtWidgets.QLabel(self.widget_2)
        sizePolicy = QtWidgets.QSizePolicy(
            QtWidgets.QSizePolicy.MinimumExpanding,
            QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.label_2.sizePolicy().hasHeightForWidth())
        self.label_2.setSizePolicy(sizePolicy)
        self.label_2.setStyleSheet("color: #0277BD;")
        self.label_2.setObjectName("label_2")
        self.horizontalLayout_5.addWidget(self.label_2)
        self.label_6 = QtWidgets.QLabel(self.widget_2)
        self.label_6.setStyleSheet("color: #757575;")
        self.label_6.setAlignment(QtCore.Qt.AlignRight
                                  | QtCore.Qt.AlignTrailing
                                  | QtCore.Qt.AlignVCenter)
        self.label_6.setObjectName("label_6")
        self.horizontalLayout_5.addWidget(self.label_6)

        self.pin = QtWidgets.QLabel(self.widget_2)
        self.pin.setMaximumSize(QtCore.QSize(12, 12))
        self.pin.setText("")
        self.pin.setTextFormat(QtCore.Qt.RichText)
        self.pin.setPixmap(QtGui.QPixmap("images/pin.png"))
        self.pin.setScaledContents(True)
        self.pin.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignTop)
        self.horizontalLayout_5.addWidget(self.pin)

        self.pin.hide()

        self.verticalLayout_3.addLayout(self.horizontalLayout_5)
        self.scrollArea = QtWidgets.QScrollArea(self.widget_2)
        sizePolicy = QtWidgets.QSizePolicy(
            QtWidgets.QSizePolicy.MinimumExpanding,
            QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.scrollArea.sizePolicy().hasHeightForWidth())
        self.scrollArea.setSizePolicy(sizePolicy)
        self.scrollArea.setStyleSheet("""
        QScrollArea {
            background-color: #21000000; 
                border-radius: 10;
                }

        QScrollBar::add-line:vertical {
                      border: none;
                            background: #00000000;
                            }

        QScrollBar::sub-line:vertical {
                      border: none;
                            background: none;
                            }

        QScrollBar::handle:vertical {
                      border: none;
                            border-radius: 2px;
                                  background: #aaffffff;
                                        width: 10px;
                                        }

        QScrollBar {
                      width: 8px;
                            margin-top: 4px;
                                  border-radius: 90;
                                        margin-right: 4px;
                                              margin-bottom: 4px;
                                              }
""")
        self.scrollArea.setHorizontalScrollBarPolicy(
            QtCore.Qt.ScrollBarAlwaysOff)
        self.scrollArea.setSizeAdjustPolicy(
            QtWidgets.QAbstractScrollArea.AdjustIgnored)
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setObjectName("scrollArea")
        self.scrollAreaWidgetContents = QtWidgets.QWidget()
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 627, 427))
        self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
        self.verticalLayout_4 = QtWidgets.QVBoxLayout(
            self.scrollAreaWidgetContents)
        self.verticalLayout_4.setObjectName("verticalLayout_4")
        self.label_3 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
        font = QtGui.QFont()
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.label_3.setFont(font)
        self.label_3.setStyleSheet("background: none; color: #ddd;")
        self.label_3.setTextInteractionFlags(QtCore.Qt.LinksAccessibleByMouse
                                             | QtCore.Qt.TextSelectableByMouse)
        self.label_3.setObjectName("label_3")
        self.label_3.setWordWrap(True)
        self.verticalLayout_4.addWidget(self.label_3)
        self.line = QtWidgets.QFrame(self.scrollAreaWidgetContents)
        self.line.setStyleSheet("background: #121212;")
        self.line.setFrameShape(QtWidgets.QFrame.HLine)
        self.line.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line.setObjectName("line")
        self.verticalLayout_4.addWidget(self.line)
        self.label_4 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
        sizePolicy = QtWidgets.QSizePolicy(
            QtWidgets.QSizePolicy.Preferred,
            QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.label_4.sizePolicy().hasHeightForWidth())
        self.label_4.setSizePolicy(sizePolicy)
        self.label_4.setStyleSheet("background-color: transparent;")
        self.label_4.setTextFormat(QtCore.Qt.AutoText)
        self.label_4.setAlignment(QtCore.Qt.AlignLeading | QtCore.Qt.AlignLeft
                                  | QtCore.Qt.AlignTop)
        self.label_4.setWordWrap(True)
        self.label_4.setTextInteractionFlags(QtCore.Qt.LinksAccessibleByMouse
                                             | QtCore.Qt.TextSelectableByMouse)
        self.label_4.setObjectName("label_4")
        self.verticalLayout_4.addWidget(self.label_4)
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
        self.verticalLayout_3.addWidget(self.scrollArea)
        self.horizontalLayout_6.addLayout(self.verticalLayout_3)
        self.horizontalLayout.addWidget(self.widget_2)
        self.verticalLayout.addLayout(self.horizontalLayout)

        self.verticalLayout_4.addWidget(self.label_4)

        self.scrollArea.setWidget(self.scrollAreaWidgetContents)

        self.verticalLayout_3.addWidget(self.scrollArea)

        self.horizontalLayout_2 = QHBoxLayout()
        self.horizontalLayout_2.setObjectName(u"horizontalLayout_2")
        self.horizontalSpacer_2 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                              QSizePolicy.Minimum)

        self.horizontalLayout_2.addItem(self.horizontalSpacer_2)

        self.label_5 = QLabel(self.widget_2)
        self.label_5.setObjectName(u"label_5")
        sizePolicy6 = QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Preferred)
        sizePolicy6.setHorizontalStretch(0)
        sizePolicy6.setVerticalStretch(0)
        sizePolicy6.setHeightForWidth(
            self.label_5.sizePolicy().hasHeightForWidth())
        self.label_5.setSizePolicy(sizePolicy6)
        self.label_5.setCursor(QCursor(Qt.PointingHandCursor))
        self.label_5.setStyleSheet(u"color: lightblue;")
        self.label_5.setAlignment(Qt.AlignRight | Qt.AlignTrailing
                                  | Qt.AlignVCenter)

        self.horizontalLayout_2.addWidget(self.label_5)

        self.verticalLayout_3.addLayout(self.horizontalLayout_2)

        self.label_5.hide()

        self.thread = QThread(self)
        self.thread.start()

        self.downloader = Downloader()
        self.downloader.moveToThread(self.thread)
        self.downloader.resultsChanged.connect(self.on_resultsChanged)

        self.retranslateUi(self)
Beispiel #51
0
 def enterEvent(self, event):
     self.font.setUnderline(True)
     self.setFont(self.font)
     self.app.setOverrideCursor(QCursor(Qt.PointingHandCursor))
     return QLabel.enterEvent(self, event)
Beispiel #52
0
    def FillPhotosByFiles(self, files):

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        # set flag so other routines will know that we're adding new files to db
        self.photosAlreadyInDb = False

        # create list to hold names of allowable files, including jpgs and tiffs
        # we'll be adding these files to the db once the user provides the meta data for them
        allowedPhotoFiles = []

        # remove non-image files from the list
        row = 0
        for fileName in files:

            QApplication.processEvents()

            # get file extension to process only jpg and tiff image files
            photoFileExtension = os.path.splitext(fileName)[1]

            # only process jpg and tiff files
            if photoFileExtension.lower() in [".jpg", ".jpeg", ".tif", "tiff"]:

                allowedPhotoFiles.append([row, fileName])

            row += 1

        # divide files into four groups, one for each thread
        # we're using threads to divide up the work of creating pixmaps for each image

        if len(allowedPhotoFiles) > 3:

            filesPerThread = divmod(len(allowedPhotoFiles), 4)[0]

            thread1Files = allowedPhotoFiles[0:filesPerThread]
            thread2Files = allowedPhotoFiles[filesPerThread:2 * filesPerThread]
            thread3Files = allowedPhotoFiles[2 * filesPerThread:3 *
                                             filesPerThread]
            thread4Files = allowedPhotoFiles[3 * filesPerThread:]

        else:

            # fewer than four files were selected, so let's not use more than one thread
            thread1Files = allowedPhotoFiles
            thread2Files = []
            thread3Files = []
            thread4Files = []

        # provide threads with starting data and run the threads
        if len(thread1Files) > 0:
            self.thread1.parent = self
            self.thread1.threadNumber = 1
            self.thread1.fileNames = thread1Files
            self.thread1.start()
        else:
            self.thread1Finished = True

        if len(thread2Files) > 0:
            self.thread2.parent = self
            self.thread2.threadNumber = 2
            self.thread2.fileNames = thread2Files
            self.thread2.start()
        else:
            self.thread2Finished = True

        if len(thread3Files) > 0:
            self.thread3.parent = self
            self.thread3.threadNumber = 3
            self.thread3.fileNames = thread3Files
            self.thread3.start()
        else:
            self.thread3Finished = True

        if len(thread4Files) > 0:
            self.thread4.parent = self
            self.thread4.threadNumber = 4
            self.thread4.fileNames = thread4Files
            self.thread4.start()
        else:
            self.thread4Finished = True
Beispiel #53
0
    def __init__(self, pkg: PackageView, http_client: HttpClient,
                 icon_cache: MemoryCache, i18n: I18n,
                 screenshots: List[QPixmap], logger: logging.Logger):
        super(ScreenshotsDialog, self).__init__()
        self.setWindowTitle(str(pkg))
        self.screenshots = screenshots
        self.logger = logger
        self.loaded_imgs = []
        self.download_threads = []
        self.resize(1280, 720)
        self.i18n = i18n
        self.http_client = http_client
        self.progress_bar = QProgressBar()
        self.progress_bar.setCursor(QCursor(Qt.WaitCursor))
        self.progress_bar.setStyleSheet(styles.PROGRESS_BAR)
        self.progress_bar.setMaximumHeight(10 if QApplication.instance().style(
        ).objectName().lower() == 'windows' else 6)
        self.progress_bar.setTextVisible(False)
        self.thread_progress = AnimateProgress()
        self.thread_progress.signal_change.connect(self._update_progress)
        self.thread_progress.start()

        # THERE ARE CRASHES WITH SOME RARE ICONS ( like insomnia ). IT CAN BE A QT BUG. IN THE MEANTIME, ONLY THE TYPE ICON WILL BE RENDERED
        #
        # icon_data = icon_cache.get(pkg.model.icon_url)
        #
        # if icon_data and icon_data.get('icon'):
        #     self.setWindowIcon(icon_data.get('icon'))
        # else:
        #     self.setWindowIcon(QIcon(pkg.model.get_type_icon_path()))
        self.setWindowIcon(QIcon(pkg.model.get_type_icon_path()))
        self.setLayout(QVBoxLayout())

        self.img = QLabel()
        self.layout().addWidget(self.img)

        self.bottom_bar = QToolBar()

        self.bt_back = QPushButton(
            ' < ' + self.i18n['screenshots.bt_back.label'].capitalize())
        self.bt_back.setCursor(QCursor(Qt.PointingHandCursor))
        self.bt_back.clicked.connect(self.back)
        self.ref_bt_back = self.bottom_bar.addWidget(self.bt_back)
        self.bottom_bar.addWidget(new_spacer(50))

        self.img_label = QLabel()
        self.img_label.setCursor(QCursor(Qt.WaitCursor))
        self.img_label.setStyleSheet(
            'QLabel { font-weight: bold; text-align: center }')
        self.ref_img_label = self.bottom_bar.addWidget(self.img_label)
        self.ref_img_label.setVisible(False)
        self.ref_progress_bar = self.bottom_bar.addWidget(self.progress_bar)
        self.bottom_bar.addWidget(new_spacer(50))

        self.bt_next = QPushButton(
            self.i18n['screenshots.bt_next.label'].capitalize() + ' > ')
        self.bt_next.setCursor(QCursor(Qt.PointingHandCursor))
        self.bt_next.clicked.connect(self.next)
        self.ref_bt_next = self.bottom_bar.addWidget(self.bt_next)

        self.layout().addWidget(self.bottom_bar)

        self.img_idx = 0

        for idx, s in enumerate(self.screenshots):
            t = Thread(target=self._download_img, args=(idx, s), daemon=True)
            t.start()

        self._load_img()
    def __init__(self):
        QWidget.__init__(self)

        self.setWindowTitle("SRMS - Student Result Monitoring System !!")
        self.setWindowIcon(QIcon("Images/hist.png"))

        width = 960
        height = 630
        self.setMinimumSize(width, height)
        self.setGeometry(100, 100, 300, 200)

        oImage = QImage("solar_system.png")
        sImage = oImage.scaled(QSize(1700, 1000))
        palette = QPalette()

        palette.setBrush(QPalette.Window, QBrush(sImage))
        self.setPalette(palette)

        vlayout = QtWidgets.QVBoxLayout()
        #hlayout = QtWidgets.QHBoxLayout()
        #grid = QGridLayout()
        #grid.setSpacing(10)

        vlayout.addStretch(2)
        self.text1 = QLabel("Let's get started!", self)
        self.text1.setFont(headfont)
        #grid.addWidget(self.text1,0,0)
        #self.text1.move(150,150)
        vlayout.addWidget(self.text1)

        self.text2 = QLabel("explore visualization and improve your analysis",
                            self)
        self.text2.setFont(smallfont)
        vlayout.addWidget(self.text2)
        vlayout.addStretch(1)

        css = """
            border-radius: 5px;
            border: 1px solid blue;
            font-size: 30px;
            padding: 10px;
            margin: 5px;
            background-color: #FCF9F9;
            Layout.fillWidth: true;   
            """

        self.analysis = QPushButton("Start Analysis...", self)
        self.analysis.setFont(smallfont)
        self.analysis.setStyleSheet(css)
        vlayout.addWidget(self.analysis)
        self.analysis.setFixedWidth(500)
        self.analysis.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
        self.analysis.clicked.connect(self.messageBox)

        self.prediction = QPushButton("Start Prediction...", self)
        self.prediction.setFont(smallfont)
        self.prediction.setStyleSheet(css)
        vlayout.addWidget(self.prediction)
        self.prediction.setFixedWidth(500)
        self.prediction.setCursor(QCursor(QtCore.Qt.PointingHandCursor))

        self.unknown = QPushButton("Show User Guides...", self)
        self.unknown.setFont(smallfont)
        self.unknown.setStyleSheet(css)
        vlayout.addWidget(self.unknown)
        self.unknown.setFixedWidth(500)
        self.unknown.setCursor(QCursor(QtCore.Qt.PointingHandCursor))

        #vlayout.fillWidth: true;
        vlayout.addStretch(3)

        self.setLayout(vlayout)
        self.showMaximized()
        self.show()
    def __init__(self, root_folder, version, is_latest, parent):
        super(B3dItemLayout, self).__init__(None)
        self.is_latest = is_latest

        self.btn_open_style = \
            ("""QPushButton[IsRunning=false]
                {
                    color: rgb(255, 255, 255);
                    background-color: rgb(51, 51, 51);
                    border-style: solid;
                    border-color: rgb(51, 51, 51);
                    border-width: 6px;
                }

                QPushButton[IsRunning=false]:pressed
                {
                    background-color: rgb(80, 80, 80);
                    border-color: rgb(80, 80, 80);
                }

                QPushButton[IsRunning=false]:hover
                {
                    background-color: rgb(80, 80, 80);
                    border-color: rgb(80, 80, 80);
                }

                QPushButton[IsRunning=true]
                {
                    color: rgb(255, 255, 255);
                    background-color: rgb(204, 102, 51);
                    border-style: solid;
                    border-color: rgb(204, 102, 51);
                    border-width: 6px;
                }

                QPushButton[IsRunning=true]:pressed
                {
                    background-color: rgb(223, 121, 70);
                    border-color: rgb(223, 121, 70);
                }

                QPushButton[IsRunning=true]:hover
                {
                    background-color: rgb(223, 121, 70);
                    border-color: rgb(223, 121, 70);
                }""")

        self.btn_delete_style = \
            ("""QPushButton[IsRunning=false]
                {
                    color: rgb(255, 255, 255);
                    background-color: rgb(51, 51, 51);
                    border-style: solid;
                    border-color: rgb(51, 51, 51);
                    border-width: 0px 4px 0px 4px;
                    qproperty-icon: url(:/icons/delete.png);
                    qproperty-iconSize: 20px;
                }

                QPushButton[IsRunning=false]:pressed
                {
                    background-color: rgb(80, 80, 80);
                    border-color: rgb(80, 80, 80);
                }

                QPushButton[IsRunning=false]:hover
                {
                    background-color: rgb(80, 80, 80);
                    border-color: rgb(80, 80, 80);
                }

                QPushButton[IsRunning=true]
                {
                    color: rgb(255, 255, 255);
                    background-color: rgb(0, 122, 204);
                    border-style: solid;
                    border-color: rgb(0, 122, 204);
                    border-width: 0px 13px 0px 13px;
                    qproperty-icon: none;
                }

                QPushButton[IsRunning=true]:pressed
                {
                    background-color: rgb(80, 80, 80);
                    border-color: rgb(80, 80, 80);
                }

                QPushButton[IsRunning=true]:hover
                {
                    background-color: rgb(80, 80, 80);
                    border-color: rgb(80, 80, 80);
                }""")

        self.platform = get_platform()

        if self.platform == 'Windows':
            blender_exe = "blender.exe"
        elif self.platform == 'Linux':
            blender_exe = "blender"

        self.parent = parent
        self.root_folder = root_folder
        self.version = version
        self.processes = []
        self.mtime = os.path.getmtime(
            os.path.join(root_folder, version, blender_exe))

        self.setContentsMargins(6, 0, 6, 0)
        self.setSpacing(0)

        b3d_exe = os.path.join(root_folder, version, blender_exe)

        if self.platform == 'Windows':
            info = subprocess.check_output([b3d_exe, "-v"],
                                           creationflags=CREATE_NO_WINDOW,
                                           shell=True,
                                           stderr=DEVNULL,
                                           stdin=DEVNULL).decode('UTF-8')
        elif self.platform == 'Linux':
            info = subprocess.check_output([b3d_exe, "-v"],
                                           shell=False,
                                           stderr=DEVNULL,
                                           stdin=DEVNULL).decode('UTF-8')

        ctime = re.search("build commit time: " + "(.*)", info)[1].rstrip()
        cdate = re.search("build commit date: " + "(.*)", info)[1].rstrip()
        self.git = re.search("build hash: " + "(.*)", info)[1].rstrip()
        strptime = time.strptime(cdate + ' ' + ctime, "%Y-%m-%d %H:%M")

        self.btnOpen = QPushButton(
            "Git-%s | %s" % (self.git, time.strftime("%d-%b-%H:%M", strptime)))
        self.btnOpen.clicked.connect(self.open)

        self.set_is_latest(self.is_latest)

        self.btnOpen.setFont(QFont("MS Shell Dlg 2", 10))
        self.btnOpen.setCursor(QCursor(Qt.PointingHandCursor))
        self.btnOpen.setStyleSheet(self.btn_open_style)
        self.btnOpen.setProperty('IsRunning', False)

        self.btnDelete = QPushButton("")
        self.btnDelete.setFlat(True)
        self.btnDelete.setToolTip("Delete From Drive")
        self.btnDelete.setSizePolicy(QSizePolicy.Maximum,
                                     QSizePolicy.Preferred)
        self.btnDelete.setCursor(QCursor(Qt.PointingHandCursor))
        self.btnDelete.clicked.connect(lambda: self.delete())
        self.btnDelete.setStyleSheet(self.btn_delete_style)
        self.btnDelete.setProperty('IsRunning', False)

        self.addWidget(self.btnOpen)
        self.addWidget(self.btnDelete)
Beispiel #56
0
    def show_pkg_actions(self, pkg: PackageView):
        menu_row = QMenu()
        menu_row.setCursor(QCursor(Qt.PointingHandCursor))

        if pkg.model.installed:

            if pkg.model.has_history():
                action_history = QAction(
                    self.i18n["manage_window.apps_table.row.actions.history"])
                action_history.setIcon(
                    QIcon(resource.get_path('img/history.svg')))

                def show_history():
                    self.window.begin_show_history(pkg)

                action_history.triggered.connect(show_history)
                menu_row.addAction(action_history)

            if pkg.model.can_be_downgraded():
                action_downgrade = QAction(
                    self.i18n["manage_window.apps_table.row.actions.downgrade"]
                )

                def downgrade():
                    if dialog.ask_confirmation(
                            title=self.i18n[
                                'manage_window.apps_table.row.actions.downgrade'],
                            body=self._parag(self.i18n[
                                'manage_window.apps_table.row.actions.downgrade.popup.body']
                                             .format(self._bold(str(pkg)))),
                            i18n=self.i18n):
                        self.window.begin_downgrade(pkg)

                action_downgrade.triggered.connect(downgrade)
                action_downgrade.setIcon(
                    QIcon(resource.get_path('img/downgrade.svg')))
                menu_row.addAction(action_downgrade)

            if pkg.model.supports_ignored_updates():
                if pkg.model.is_update_ignored():
                    action_ignore_updates = QAction(self.i18n[
                        "manage_window.apps_table.row.actions.ignore_updates_reverse"]
                                                    )
                    action_ignore_updates.setIcon(
                        QIcon(
                            resource.get_path(
                                'img/revert_update_ignored.svg')))
                else:
                    action_ignore_updates = QAction(self.i18n[
                        "manage_window.apps_table.row.actions.ignore_updates"])
                    action_ignore_updates.setIcon(
                        QIcon(resource.get_path('img/ignore_update.svg')))

                def ignore_updates():
                    self.window.begin_ignore_updates(pkg)

                action_ignore_updates.triggered.connect(ignore_updates)
                menu_row.addAction(action_ignore_updates)

        if bool(pkg.model.get_custom_supported_actions()):
            for action in pkg.model.get_custom_supported_actions():
                item = QAction(self.i18n[action.i18_label_key])

                if action.icon_path:
                    item.setIcon(QIcon(action.icon_path))

                def custom_action():
                    if dialog.ask_confirmation(
                            title=self.i18n[action.i18_label_key],
                            body=self._parag('{} {} ?'.format(
                                self.i18n[action.i18_label_key],
                                self._bold(str(pkg)))),
                            i18n=self.i18n):
                        self.window.begin_execute_custom_action(pkg, action)

                item.triggered.connect(custom_action)
                menu_row.addAction(item)

        menu_row.adjustSize()
        menu_row.popup(QCursor.pos())
        menu_row.exec_()
Beispiel #57
0
 def mouseReleaseEvent(self, QMouseEvent):
     self.m_flag = False
     self.setCursor(QCursor(Qt.ArrowCursor))
Beispiel #58
0
    def setupUi(self,
                Form,
                username=None,
                userid=1,
                host='192.168.2.171',
                simid=None,
                reset=False):
        self.host = host
        self.username = username
        self.userid = userid
        self.simid = simid
        self.readonly = (simid is not None)
        self.showsettings = False
        self.currentindex = 0
        self.usedefaultsettings = True

        self.db = connector.connect(host=self.host,
                                    user="******",
                                    passwd="Sequal1234",
                                    database="simulation",
                                    use_pure=True)
        self.db.autocommit = True
        self.simrunning = False
        # self.esrunning = False
        if not reset:
            self.thread = None
            self.thread = QThread()
        self.cppath = getcwd() + "\\cutplans\\"
        self.logpath = getcwd() + "\\logs\\"
        self.shifts = 2
        self.simShift = 1
        index = []
        for i in range(1, self.shifts + 1):
            index.append(str(i))
        index.append("Total")
        cols = [
            "RunTime", "LogsCut", "Production", "LogVolume", "Recovery",
            "LogRate", "Uptime", "MSLDT", "BSLDT", "TSLDT", "SawdustVol"
        ]
        self.results = DataFrame(index=index, columns=cols)

        # self.OpenExtendSim()

        Form.setObjectName("Form")
        Form.resize(900, 750)
        Form.setMinimumSize(QSize(900, 750))
        Form.setStyleSheet("background-color: rgb(255, 255, 255);\n"
                           "color: rgb(0, 115, 119);")
        if Form.layout() is not None:
            QWidget().setLayout(Form.layout())
        self.verticalLayout = QVBoxLayout(Form)
        self.verticalLayout.setObjectName("verticalLayout")

        ss = \
            """
            QToolButton {
                background-color: qlineargradient(spread:pad,
                    x1:0, y1:0, x2:1, y2:1, stop:0 rgba(0, 115,
                    119, 255), stop:1 rgb(4, 147, 131));
                color: white;
                border: None;
                border-radius: 2px;
                font: 11pt "Tahoma";
                padding: 5px;
                margin-right: 20px;
            }
            """
        self.detailsLayout = QHBoxLayout()
        self.closeButton = QToolButton(Form)
        self.closeButton.setObjectName("closeButton")
        self.closeButton.setStyleSheet(ss)
        self.closeButton.setCursor(QCursor(Qt.PointingHandCursor))
        icon1 = QIcon("images/close.png")
        self.closeButton.setIcon(icon1)
        self.closeButton.setVisible(self.readonly)
        self.detailsLayout.addWidget(self.closeButton)
        self.nameLabel = QLabel(Form)
        self.nameLabel.setText("Name: ")
        self.nameLabel.setStyleSheet(
            "QLabel {"
            "background: none; font: 15pt \"Tahoma\";font-weight: bold;"
            "}")
        self.detailsLayout.addWidget(self.nameLabel)
        self.nameTextbox = QLineEdit(Form)
        self.nameTextbox.setText("Simulation")
        self.nameTextbox.setStyleSheet(
            "QLineEdit {\n"
            "background: none; font: 15pt \"Tahoma\";"
            "border: 1px solid rgb(0,115,119);\n"
            "}\n"
            "QLineEdit:disabled {border: none;}")
        self.detailsLayout.addWidget(self.nameTextbox)
        h = self.nameTextbox.size().height()
        self.closeButton.setMinimumSize(QSize(h, h))
        self.closeButton.setIconSize(QSize(h - 10, h - 10))
        self.PlayButton = QToolButton(Form)
        self.PlayButton.setObjectName("PlayButton")
        self.PlayButton.setStyleSheet(ss)
        self.PlayButton.setMinimumSize(QSize(h, h))
        self.PlayButton.setCursor(QCursor(Qt.PointingHandCursor))
        icon1 = QIcon("images/play.png")
        self.PlayButton.setIcon(icon1)
        self.PlayButton.setIconSize(QSize(h - 10, h - 10))
        self.PlayButton.setVisible(False)
        self.detailsLayout.addWidget(self.PlayButton)
        hSpacer = QSpacerItem(40, 20, QSizePolicy.Expanding,
                              QSizePolicy.Minimum)
        self.detailsLayout.addItem(hSpacer)
        self.CreateNewButton = QToolButton(Form)
        self.CreateNewButton.setObjectName("CreateNewButton")
        self.CreateNewButton.setStyleSheet(ss)
        self.CreateNewButton.setMinimumSize(QSize(h, h))
        self.CreateNewButton.setText("Create New")
        self.CreateNewButton.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        icon1 = QIcon("images/new.png")
        self.CreateNewButton.setIcon(icon1)
        self.CreateNewButton.setIconSize(QSize(h - 10, h - 10))
        self.CreateNewButton.setCursor(QCursor(Qt.PointingHandCursor))
        self.CreateNewButton.setVisible(False)
        self.detailsLayout.addWidget(self.CreateNewButton)
        self.SettingsButton = QToolButton(Form)
        self.SettingsButton.setObjectName("SettingsButton")
        self.SettingsButton.setStyleSheet(ss)
        self.SettingsButton.setMinimumSize(QSize(h, h))
        self.SettingsButton.setCursor(QCursor(Qt.PointingHandCursor))
        icon1 = QIcon("images/settings.png")
        self.SettingsButton.setIcon(icon1)
        self.SettingsButton.setIconSize(QSize(h - 10, h - 10))
        self.detailsLayout.addWidget(self.SettingsButton)
        self.detailsLayout.setSpacing(5)
        self.verticalLayout.addLayout(self.detailsLayout)

        self.mainhorilayout = QHBoxLayout()
        self.ResultsArea = QScrollArea(Form)
        self.ResultsWidget = ResultsWidget()
        self.ResultsWidget.setupUi(self.ResultsArea)
        self.ResultsWidget.setObjectName("ResultsWidget")
        self.ResultsArea.setWidget(self.ResultsWidget)
        self.ResultsArea.setWidgetResizable(True)
        self.ResultsArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.ResultsArea.setFrameShape(QFrame.NoFrame)
        self.mainhorilayout.addWidget(self.ResultsArea)

        self.StackedWidget = QWidget(Form)
        self.StackedLayout = QStackedLayout(self.StackedWidget)
        self.CutplanArea = QScrollArea(self.StackedWidget)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.CutplanArea.sizePolicy().hasHeightForWidth())
        self.CutplanArea.setSizePolicy(sizePolicy)
        self.CutplanArea.setMinimumSize(QSize(0, 250))
        self.CutplanArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        # self.CutplanArea.setSizeAdjustPolicy(
        #    QAbstractScrollArea.AdjustToContents)
        self.CutplanArea.setWidgetResizable(True)
        self.CutplanArea.setFrameShape(QFrame.NoFrame)
        self.CutplanArea.setObjectName("CutplanArea")
        self.CPWidget = QWidget()
        self.Cutplans = CutplanWidget()
        self.Cutplans.setupUi(self.CPWidget)
        self.Cutplans.setObjectName("Cutplans")
        self.CutplanArea.setWidget(self.CPWidget)
        self.StackedLayout.addWidget(self.CutplanArea)
        self.StackedLayout.setSpacing(0)
        self.StackedLayout.setContentsMargins(0, 0, 0, 0)
        self.StackedWidget.setStyleSheet('background-color:rhba(0,0,0,0);')
        self.StackedWidget.setMaximumWidth(250)
        self.AddWindow = AddCutplanDialog(self.StackedWidget)
        self.AddWindow.setupUi(None, "support/cpquery.sql", self.Cutplans.host)
        self.StackedLayout.addWidget(self.AddWindow)
        self.SettingsWidget = QWidget(self.StackedWidget)
        self.SettingsUI = SettingsWindow(self.SettingsWidget)
        self.SettingsUI.setupUi(self.SettingsWidget)
        self.GetDefaultSettings()
        self.StackedLayout.addWidget(self.SettingsWidget)
        self.StackedLayout.setCurrentIndex(0)
        self.mainhorilayout.addWidget(self.StackedWidget)

        self.verticalLayout.addLayout(self.mainhorilayout)
        self.verticalLayout.setContentsMargins(50, 30, 50, 30)
        self.verticalLayout.setSpacing(50)
        self.timer = QTimer(self)
        self.timer.setInterval(100)

        self.timer.timeout.connect(self.UpdateGUI)
        self.PlayButton.clicked.connect(self.OnPlay)
        self.SettingsButton.clicked.connect(self.OnSettings)
        self.Cutplans.newcutplans.connect(self.ThreadSetup)
        self.Cutplans.AddButton.clicked.connect(self.AddClick)
        self.Cutplans.cploadfinish.connect(self.showPlayButton)
        self.AddWindow.buttonBox.rejected.connect(self.AddReject)
        self.AddWindow.buttonBox.accepted.connect(self.AddAccept)
        self.SettingsUI.buttonbox.accepted.connect(self.GetSettings)
        self.SettingsUI.buttonbox.rejected.connect(self.SendSettings)

        self.retranslateUi(Form)
        QMetaObject.connectSlotsByName(Form)
Beispiel #59
0
 def open_tasks_list_context_menu(self):
     self.tasks_list_context_menu.exec_(QCursor.pos())
 def showContextMenu(self, pos):
     if self.itemAt(pos) and self.itemAt(pos).parent():
         self.contextMenu.move(QCursor.pos())
         self.contextMenu.show()