示例#1
0
 def show_game_context(self):
     gamelist = self.get_current_list()
     if gamelist[0].itemAt(gamelist[0].mapFromGlobal(QCursor.pos())) is gamelist[0].currentItem():
             if gamelist[1] == 0:
                 self.installedGames_menu.exec_(QCursor.pos())
             else:
                 self.ownedGames_menu.exec_(QCursor.pos())
示例#2
0
 def show_game_context(self):
     gamelist = self.get_current_list()
     if gamelist[0].itemAt(gamelist[0].mapFromGlobal(
             QCursor.pos())) is gamelist[0].currentItem():
         if gamelist[1] == 0:
             self.installedGames_menu.exec_(QCursor.pos())
         else:
             self.ownedGames_menu.exec_(QCursor.pos())
示例#3
0
    def setMousePos(self):
        l = len(self.returns_stack) 
        if l and isinstance(self.returns_stack[l-1],QPoint):
            pos = self.returns_stack.pop()
#             pos.setX(pos.x()+10)
#             pos.setY(pos.y()+10)
            pos_map = Jaime.instance.view.mapToGlobal(pos)
            scroll_pos = Jaime.instance.view.page().mainFrame().scrollPosition()
            pos_map.setX(pos_map.x()-scroll_pos.x())
            pos_map.setY(pos_map.y()-scroll_pos.y())
            self.logger.info('setMousePos. setting mouse position on %s ' % pos_map)
            QCursor.setPos(pos_map)
    def __init__(self, define_path='', define_type=None):
        super(MTTFilterFileDialog, self).__init__(get_maya_window())

        self.supported_node_type = sorted([
            node_type for (node_type, nice, attr) in MTTSettings.SUPPORTED_TYPE
        ])

        self.defined_path = (define_path if os.path.isdir(define_path)
                             or define_path == SOURCEIMAGES_TAG else None)

        self.defined_type = (define_type if define_type
                             in self.supported_node_type else None)

        self.path_edit = None
        self.filter_reset_btn = None
        self.filter_line = None
        self.parent_folder_btn = None
        self.files_model = None
        self.files_list = None
        self.bookmark_list = None
        self.bookmark_list_sel_model = None
        self.types = None

        # move window to cursor position
        win_geo = MTTSettings.value('FilterFileDialog/windowGeometry',
                                    QRect(0, 0, 400, 300))
        self.setGeometry(win_geo)
        mouse_pos = QCursor.pos()
        mouse_pos.setX(mouse_pos.x() - (win_geo.width() * 0.5))
        self.move(mouse_pos)

        self.__create_ui()

        self.filter_line.setFocus()
        self.on_change_root_path(self.defined_path or SOURCEIMAGES_TAG)
 def mousePressEvent(self, event):
     if event.button() == Qt.MidButton:
         QApplication.setOverrideCursor(QCursor(Qt.SizeHorCursor))
         self._pan_pos = event.globalPos()
         event.accept()
     else:
         event.ignore()
示例#6
0
    def loadContextMenu(self, *args):

        menu = QMenu(self.w_tree)
        path = self.w_tree.currentItem().text(0)
        if os.path.isdir(path):
            dirPath = path
        else:
            dirPath = os.path.dirname(path)
        if os.path.exists(dirPath):
            menu.addAction(unicode("Open Folder", errors='replace'),
                           self.openFolder)
        menu.addAction(unicode("Copy Path", errors='replace'), self.copyPath)
        separator = QAction(self.w_tree)
        separator.setSeparator(True)
        menu.addAction(separator)
        menu.addAction(unicode("Replace Path", errors='replace'),
                       self.replacePath)
        separator = QAction(self.w_tree)
        separator.setSeparator(True)
        menu.addAction(separator)
        if self.unusedExists():
            menu.addAction(unicode("Remove Unused Files", errors='replace'),
                           self.removeUnused)
        pos = QCursor.pos()
        point = QtCore.QPoint(pos.x() + 10, pos.y())
        menu.exec_(point)
示例#7
0
    def mouse_position(self):
        """ Returns the current mouse position (in screen coordinates) as a
            tuple of the form: (x,y).
        """
        position = QCursor.pos()

        return (position.x(), position.y())
示例#8
0
    def leaveEvent(self,event):
        r = self.edit_panel.geometry()
        # Tested this, but it doesn't work : if self.edit_panel.underMouse() == False:
        if not self.edit_panel.rect().contains(self.edit_panel.mapFromGlobal(QCursor.pos())):
            self.edit_panel.hide()

        return super(PoppingContactDataPlateWidget,self).leaveEvent(event)
    def calculixFinished(self, exitCode):
        print "calculixFinished()", exitCode
        print self.Calculix.state()
        out = self.Calculix.readAllStandardOutput()
        print out
        if out:
            self.OutStr = self.OutStr + unicode(out).replace('\n', '<br>')
            self.formUi.textEdit_Output.setText(self.OutStr)

        self.Timer.stop()

        self.OutStr = self.OutStr + '<font color="#0000FF">{0:4.1f}:</font> '.format(
            time.time() -
            self.Start) + '<font color="#00FF00">Calculix done!</font><br>'
        self.formUi.textEdit_Output.setText(self.OutStr)

        self.formUi.pushButton_generate.setText("Re-run Calculix")
        print "Loading results...."
        self.OutStr = self.OutStr + '<font color="#0000FF">{0:4.1f}:</font> '.format(
            time.time() - self.Start) + 'Loading result sets...<br>'
        self.formUi.textEdit_Output.setText(self.OutStr)
        self.formUi.label_Time.setText('Time: {0:4.1f}: '.format(time.time() -
                                                                 self.Start))

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        CalculixLib.importFrd(self.Basename + '.frd',
                              FemGui.getActiveAnalysis())
        QApplication.restoreOverrideCursor()
        self.OutStr = self.OutStr + '<font color="#0000FF">{0:4.1f}:</font> '.format(
            time.time() - self.Start
        ) + '<font color="#00FF00">Loading results done!</font><br>'
        self.formUi.textEdit_Output.setText(self.OutStr)
        self.formUi.label_Time.setText('Time: {0:4.1f}: '.format(time.time() -
                                                                 self.Start))
示例#10
0
    def calculixFinished(self, exitCode):
        print "calculixFinished()", exitCode
        print self.Calculix.state()
        out = self.Calculix.readAllStandardOutput()
        print out
        if out:
            self.femConsoleMessage(unicode(out).replace('\n', '<br>'))

        self.Timer.stop()

        self.femConsoleMessage("Calculix done!", "#00FF00")

        self.form.pushButton_generate.setText("Re-run Calculix")
        print "Loading results...."
        self.femConsoleMessage("Loading result sets...")
        self.form.label_Time.setText('Time: {0:4.1f}: '.format(time.time() -
                                                               self.Start))

        if os.path.isfile(self.Basename + '.frd'):
            QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
            CalculixLib.importFrd(self.Basename + '.frd',
                                  FemGui.getActiveAnalysis())
            QApplication.restoreOverrideCursor()
            self.femConsoleMessage("Loading results done!", "#00FF00")
        else:
            self.femConsoleMessage(
                "Loading results failed! Results file doesn\'t exist",
                "#FF0000")
        self.form.label_Time.setText('Time: {0:4.1f}: '.format(time.time() -
                                                               self.Start))
示例#11
0
    def popup_menu(self, position):

        selected_row = self.view.rowAt(position.y())

        if selected_row >= 0 and self._used_categories and len(
                self._used_categories) > 1:
            category_menu = QMenu(_("Categories"))
            selected_doc = self.model.object_at(selected_row)

            category_actions = []
            for category in self._used_categories:
                a = QAction(category.full_name, category_menu)
                a.setData(category)

                a.setEnabled(selected_doc.document_category_id !=
                             category.document_category_id)

                category_menu.addAction(a)
                category_actions.append(a)

            action = category_menu.exec_(QCursor.pos())

            if action:
                new_category = action.data()

                if selected_doc.document_category_id != new_category.document_category_id:
                    selected_doc.document_category_id = new_category.document_category_id
                    self.model.signal_object_change(selected_doc)
示例#12
0
    def __init__(self, qpart, model):
        QListView.__init__(self, qpart.viewport())
        self.setItemDelegate(HTMLDelegate(self))
        
        self._qpart = qpart
        self.setFont(qpart.font())
        
        self.setCursor(QCursor(Qt.PointingHandCursor))
        self.setFocusPolicy(Qt.NoFocus)
        
        self.setModel(model)
        
        self._selectedIndex = -1
        
        # if cursor moved, we shall close widget, if its position (and model) hasn't been updated
        self._closeIfNotUpdatedTimer = QTimer()
        self._closeIfNotUpdatedTimer.setInterval(200)
        self._closeIfNotUpdatedTimer.setSingleShot(True)

        self._closeIfNotUpdatedTimer.timeout.connect(self._afterCursorPositionChanged)
        
        qpart.installEventFilter(self)
        
        qpart.cursorPositionChanged.connect(self._onCursorPositionChanged)
        
        self.clicked.connect(lambda index: self.itemSelected.emit(index.row()))
        
        self.updateGeometry()
        self.show()
        
        qpart.setFocus()
示例#13
0
def wake_screen():
    import random, time
    from PySide.QtGui import QCursor

    time.sleep(5)

    q = QCursor()
    pos = q.pos()
    ox, oy = pos.x(), pos.y()

    def rgen():
        r = 300
        while 1:
            theta = math.radians(random.random() * 360)
            x = r * math.cos(theta)
            y = r * math.sin(theta)
            yield ox + x, oy + y

    random_point = rgen()

    for i in range(5):
        x, y = random_point.next()
        q.setPos(x, y)
        time.sleep(0.1)
    q.setPos(ox, oy)
示例#14
0
    def set_mouse_position(self, view_state, coord):
        """
        Update the mouse cursor position independently
        """

        _new_pos = view_state.getPointOnScreen(coord)

        #set the mouse position at the updated screen coordinate
        _delta_pos = SmartTuple(_new_pos).sub(self.screen_position)

        #get screen position by adding offset to the new window position
        _pos = SmartTuple.from_values(_delta_pos[0], -_delta_pos[1])\
            .add(QCursor.pos().toTuple())

        QCursor.setPos(_pos[0], _pos[1])

        self.screen_position = _pos
        self.world_position = coord
示例#15
0
    def set_mouse_position(self, coord):
        """
        Update the mouse cursor position independently
        """

        _new_pos = ViewState().getPointOnScreen(coord)

        #set the mouse position at the updated screen coordinate
        _delta_pos = _new_pos.sub(Vector(self.pos + (0.0, )))

        #get screen position by adding offset to the new window position
        _pos = Vector(QCursor.pos().toTuple() + (0.0, )).add(
            Vector(_delta_pos.x, -_delta_pos.y))

        QCursor.setPos(_pos[0], _pos[1])

        self.coordinates = Vector(coord)
        self.set_position(_new_pos)
示例#16
0
文件: _Window.py 项目: ra2003/xindex
 def menuHovered(self, action):
     settings = QSettings()
     if bool(
             int(
                 settings.value(Gopt.Key.ShowMenuToolTips,
                                Gopt.Default.ShowMenuToolTips))):
         tip = action.toolTip()
         if tip:
             QToolTip.showText(QCursor.pos(), tip, self)
def ExampleMenu_Execute():
    """a simple example showing the use of a qmenu"""
    from PySide import shiboken
    
    sianchor = Application.getQtSoftimageAnchor()
    sianchor = shiboken.wrapInstance( long(sianchor), QWidget )
    menu = ExampleMenu( sianchor )
    
    # notice the use of QCursor and exec_ call
    menu.exec_(QCursor.pos())
    def paintEvent(self, event):
        mouse_pos = self.mapFromGlobal(QCursor.pos())
        is_hover = self.contentsRect().contains(mouse_pos)

        QPushButton.paintEvent(self, event)

        painter = QPainter(self)
        painter.drawPixmap(2, 1, self.icon)
        if is_hover:
            painter.setCompositionMode(QPainter.CompositionMode_Screen)
            painter.drawPixmap(2, 1, self.icon)
示例#19
0
    def set_mouse_position(self, view_state, coord=None):
        """
        Update the mouse cursor position independently
        coord - position in world coordinates
        """

        if not coord:
            coord = self.world_position

        _new_pos = view_state.getPointOnScreen(coord)

        #set the mouse position at the updated screen coordinate
        _delta = SmartTuple._sub(_new_pos, self.screen_position)

        #get screen position by adding offset to the new window position
        _pos = SmartTuple._add((_delta[0], -_delta[1]), QCursor.pos().toTuple())

        QCursor.setPos(_pos[0], _pos[1])

        self.world_position = coord
示例#20
0
    def loadContextMenu(self):
        def cmd_loadSelected():
            selObjects = pymel.core.ls(sl=1)
            if not selObjects: return
            cuItem = self.treeWidget.currentItem()
            cuItem.setText(1, selObjects[0].name())

        menu = QMenu(self.treeWidget)
        menu.addAction("Load Object", cmd_loadSelected)
        pos = QCursor.pos()
        point = QtCore.QPoint(pos.x() + 10, pos.y())
        menu.exec_(point)
示例#21
0
文件: gui.py 项目: OSUPychron/pychron
def wake_screen():
    import random, time
    from PySide.QtGui import QCursor

    time.sleep(5)

    q = QCursor()
    pos = q.pos()
    ox, oy = pos.x(), pos.y()

    def rgen():
        r = 300
        while 1:
            theta = math.radians(random.random() * 360)
            x = r * math.cos(theta)
            y = r * math.sin(theta)
            yield ox + x, oy + y

    random_point = rgen()

    for i in range(5):
        x, y = random_point.next()
        q.setPos(x, y)
        time.sleep(0.1)
    q.setPos(ox, oy)
示例#22
0
 def __dialog_is_busy(self, isBusy):
     """This function disables/enables certain GUI elements in the main dialog box."""
     if isBusy:
         self.main_dialog.setCursor(QCursor(QtCore.Qt.WaitCursor))
         self.main_dialog.findChild(QTabWidget, 'tabset').setEnabled(False)
         self.main_dialog.findChild(QPushButton, 'paste_button').setEnabled(False)
         self.main_dialog.findChild(QRadioButton, 'simple_copy_radio').setEnabled(
             False
         )
         self.main_dialog.findChild(QPushButton, 'command_list_button').setEnabled(
             False
         )
         self.main_dialog.findChild(QRadioButton, 'standard_copy_radio').setEnabled(
             False
         )
         self.main_dialog.findChild(QCheckBox, 'delete_selections_check').setEnabled(
             False
         )
         self.main_dialog.findChild(QComboBox, 'documents_list_combobox').setEnabled(
             False
         )
     else:
         self.main_dialog.setCursor(QCursor(QtCore.Qt.ArrowCursor))
         self.main_dialog.findChild(QTabWidget, 'tabset').setEnabled(True)
         self.main_dialog.findChild(QPushButton, 'paste_button').setEnabled(True)
         self.main_dialog.findChild(QRadioButton, 'simple_copy_radio').setEnabled(
             True
         )
         self.main_dialog.findChild(QPushButton, 'command_list_button').setEnabled(
             True
         )
         self.main_dialog.findChild(QRadioButton, 'standard_copy_radio').setEnabled(
             True
         )
         self.main_dialog.findChild(QCheckBox, 'delete_selections_check').setEnabled(
             True
         )
         self.main_dialog.findChild(QComboBox, 'documents_list_combobox').setEnabled(
             True
         )
示例#23
0
    def _customMenu(self):
        selectedItems = self.pushupsListWidget.selectedItems()

        if selectedItems is not None:
            selectedItem = selectedItems[0]

            if selectedItem.parent() is not None:  # Child Item selected
                menu = QMenu()

                delete = QAction(self.pushupsListWidget)
                delete.setText("Delete this pushup")
                delete.triggered.connect(self._emitDeleteSignal)
                menu.addAction(delete)
                menu.exec_(QCursor.pos())
            else:  # Top level Item selected
                menu = QMenu()

                delete = QAction(self.pushupsListWidget)
                delete.setText("Delete this day and all of its exercises")
                delete.triggered.connect(self._emitDeleteDaySignal)
                menu.addAction(delete)
                menu.exec_(QCursor.pos())
示例#24
0
 def _customMenu(self):
     selectedItems = self.pushupsListWidget.selectedItems()
     
     if selectedItems is not None :
         selectedItem = selectedItems[0] 
         
         if selectedItem.parent() is not None : # Child Item selected
             menu = QMenu()
             
             delete = QAction(self.pushupsListWidget)
             delete.setText("Delete this pushup")
             delete.triggered.connect(self._emitDeleteSignal)
             menu.addAction(delete)
             menu.exec_(QCursor.pos())
         else : # Top level Item selected
             menu = QMenu()
          
             delete = QAction(self.pushupsListWidget)
             delete.setText("Delete this day and all of its exercises")
             delete.triggered.connect(self._emitDeleteDaySignal)
             menu.addAction(delete)
             menu.exec_(QCursor.pos())
示例#25
0
def isFocusWidget():
    """
    return true if the global qApp has any focused widgets
    """
    from PySide.QtGui import QApplication, QCursor

    focus = False
    if QApplication.instance():
        if QApplication.instance().focusWidget():
            window = QApplication.instance().focusWidget().window()
            geom = window.geometry()
            focus = geom.contains( QCursor.pos() )

    return focus
示例#26
0
def show( evt=0 ):
    
    if cmds.window( Window_global.objectName, ex=1 ):
        cmds.deleteUI( Window_global.objectName )
    
    Window_global.mainGui = Window(Window_global.mayaWin)
    Window_global.mainGui.setObjectName( Window_global.objectName )
    
    pos = Window_global.mainGui.mapFromGlobal( QCursor.pos() )
    
    Window_global.mainGui.move( pos.x()-25, pos.y()-63 )
    Window_global.mainGui.resize( Window_global.width, Window_global.height )
    
    Window_global.mainGui.show()
    def wrapper(*args, **kwargs):
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        exception = None

        try:
            rtn = func(*args, **kwargs)
        except Exception as e:
            exception = e
            rtn = None
        finally:
            QApplication.restoreOverrideCursor()

        if exception:
            raise exception

        return rtn
示例#28
0
 def wheelEvent(self, eventQWheelEvent):
     oldscale = self.scale
     self.scale += eventQWheelEvent.delta() / 1200.0
     if (self.scale < 0.1):
         self.scale = oldscale
     screenpoint = self.mapFromGlobal(QCursor.pos())
     dx, dy = screenpoint.x(), screenpoint.y()
     oldpoint = (screenpoint.x() + self.position[0],
                 screenpoint.y() + self.position[1])
     newpoint = (oldpoint[0] * (self.scale / oldscale),
                 oldpoint[1] * (self.scale / oldscale))
     self.position = (newpoint[0] - dx, newpoint[1] - dy)
     print(self.position[0])
     print(self.position[1])
     print("  ")
     self.update()
示例#29
0
 def showAttributeMenu(self, attribute):
     m = QMenu()
     m.addAction('Overlay/Filter')
     c = m.addMenu('Compare to')
     for h in self.headers:
         c.addAction(h)
     m.addAction('Sort...')
     choice = m.exec_(QCursor.pos())
     
     if choice != None:
         choice = choice.text()
         if choice == 'Overlay/Filter':
             self.changeOverlay(attribute)
         elif choice == 'Sort...':
             # TODO
             pass
         else:
             self.showScatterplot(choice,attribute)
示例#30
0
 def moveEvent(self, event):
     if self.isFloating():
         cursor_widget = self.app.widgetAt(QCursor.pos())
         if cursor_widget and (self.parent() is not cursor_widget.window()):
             target = cursor_widget
             while target and not isinstance(target, (View, Window)):
                 target = target.parent()
             if isinstance(target, View):
                 if not self.isAreaAllowed(target.dock_area) or \
                         not target.parent().accepts_view(self):
                     target = None
             if isinstance(target, Window):
                 if target.findChild(View) or not target.accepts_view(self):
                     target = None
             self.redock_target = target
         else:
             self.redock_target = None
     return super(View, self).moveEvent(event)
    def paintEvent(self, event):
        mouse_pos = self.mapFromGlobal(QCursor.pos())
        is_hover = self.contentsRect().contains(mouse_pos)

        if not self.new_ui:
            QPushButton.paintEvent(self, event)

        painter = QPainter(self)
        if self.new_ui and self.isChecked():
            painter.setRenderHint(QPainter.Antialiasing)
            painter.setPen(QPen(Qt.NoPen))
            painter.setBrush(self.highlight)
            painter.drawRoundedRect(event.rect(), 2, 2)

        painter.drawPixmap(2, 2, self.icon)

        if is_hover:
            painter.setCompositionMode(QPainter.CompositionMode_Screen)
            painter.drawPixmap(2, 2, self.icon)
示例#32
0
    def update_cursor(self, shape, size):
        self.cursor_size = size
        self.shape = shape

        cursor_pix = QPixmap(size, size)
        cursor_pix.fill(Qt.transparent)

        painter = QPainter(cursor_pix)
        painter.setPen(QColor(255, 0, 0))

        if shape == 'circle':
            painter.drawEllipse(0, 0, size - 1, size - 1)
        elif shape == 'square':
            painter.drawRect(0, 0, size - 1, size - 1)
        elif shape == "magic wand":
            magic_wand.render(painter, QRect(0, 0, 20, 20))

        cursor = QCursor(cursor_pix, 0, 0)
        self.setCursor(cursor)
        del painter
    def capture(self):
        app.processEvents()

        print "caught capture",('tmp_{}_{:'+self.fmt+'}.jpg').format(self.UID,self.capture_count)
        print "current fps",float(self.capture_count)/(time.time()-self.start_capture_time)
        if not self.snap_shots.queue.empty():
            self.snap_shots.queue.get(0)
            arrow = QPixmap(self.arrow_icon);
            self.px = QPixmap.grabWindow(QApplication.desktop().winId())
            painter = QPainter(self.px)
            painter.drawPixmap(QCursor.pos(), arrow)
            if(self.options.capture_area_sa.isChecked()):
                self.px2 = self.px.copy(self.options.sa_x.value(),
                                        self.options.sa_y.value(),
                                        self.options.sa_w.value(),
                                        self.options.sa_h.value())
            else:
                self.px2 = self.px
            self.px2.save(('tmp_{}_{:'+self.fmt+'}.jpg').format(self.UID,self.capture_count), 'jpg')
            self.capture_count+=1
    def __init__(self, define_path='', define_type=None):
        super(MTTFilterFileDialog, self).__init__(get_maya_window())

        self.supported_node_type = sorted(
            [node_type
             for (node_type, nice, attr) in MTTSettings.SUPPORTED_TYPE])

        self.defined_path = (
            define_path
            if os.path.isdir(define_path) or define_path == SOURCEIMAGES_TAG
            else None)

        self.defined_type = (
            define_type
            if define_type in self.supported_node_type
            else None)

        self.path_edit = None
        self.filter_reset_btn = None
        self.filter_line = None
        self.parent_folder_btn = None
        self.files_model = None
        self.files_list = None
        self.bookmark_list = None
        self.bookmark_list_sel_model = None
        self.types = None

        # move window to cursor position
        win_geo = MTTSettings.value(
            'FilterFileDialog/windowGeometry', QRect(0, 0, 400, 300))
        self.setGeometry(win_geo)
        mouse_pos = QCursor.pos()
        mouse_pos.setX(mouse_pos.x() - (win_geo.width() * 0.5))
        self.move(mouse_pos)

        self.__create_ui()

        self.filter_line.setFocus()
        self.on_change_root_path(self.defined_path or SOURCEIMAGES_TAG)
示例#35
0
    def handleNotification(self, note):

        tree_mediator = self.facade.retrieveMediator(TreeView2Mediator.NAME)
        """:type :TreeView2Mediator"""
        if note.name == Notes.SHOW_CONTEXT_MENU:
            vo = note.body
            """:type :ShowContextMenuVO"""
            item_type = vo.selected_item.get_type()
            self.__menu.fill(item_type)
            self.__menu.popup(QCursor().pos())

        elif note.name == Notes.CONTEXT_MENU_RENAME:
            current_name = tree_mediator.get_current_node().get_name()
            self.sendNotification(Notes.SHOW_RENAME_DIALOG,
                                  ShowRenameDialogVO(current_name))

        elif note.name == Notes.CONTEXT_MENU_REPLACE_STEP:
            self.sendNotification(Notes.SHOW_REPLACE_STEP_DIALOG)

        elif note.name == Notes.CONTEXT_MENU_SET_HOTKEY:
            cur_node_hotkey = tree_mediator.get_current_node().leaf.hotkey
            self.sendNotification(Notes.SHOW_HOTKEY_DIALOG,
                                  ShowHotkeyDialogVO(cur_node_hotkey))
示例#36
0
def open_new_shader_menu():
    """
    Open menu using QMenu with all maps
    :return: 
    """
    try:
        from PySide.QtGui import QMenu, QAction, QCursor
    except:
        from PySide2.QtGui import QCursor
        from PySide2.QtWidgets import QMenu, QAction
    maps = SuperShader._get_maps()
    if not maps:
        return
    menu = QMenu(hou.ui.mainQtWindow())
    menu.setStyleSheet(hou.ui.qtStyleSheet())
    for m in maps:
        if m.get('allow_creation'):
            menu.addAction(QAction(m['name'], menu))
    act = menu.exec_(QCursor.pos())
    if not act:
        return
    new_shader_map = ([x for x in maps if x['name'] == act.text()] or [None])[0]
    return new_shader_map
示例#37
0
    def analysePlugins(self):
        if self.check2to3Script():
            self._ui.label_2.setText('2to3.py script not found.\nPlease locate it in the Options tab.')
            return
        else:
            self._pluginUpdater._pluginUpdateDict = {}
            QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
            package = reload(sys.modules[PLUGINS_PACKAGE_NAME])
#             try:
#                 package = imp.reload(sys.modules['mapclientplugins'])
#             except Exception:
#                 package = importlib.reload(sys.modules['mapclientplugins'])
            for _, modname, ispkg in pkgutil.iter_modules(package.__path__):
                if ispkg and modname != 'imagesourcestep' and modname != 'pointcloudserializerstep':
                    self._pluginUpdater._directory = _.path
                    (plugin_init_update, plugin_resources_update, plugin_syntax_update, plugin_tabbed_indentation, resourcesDirs, tabbed_modules) = performPluginAnalysis(_.path, modname, self._resourceFiles)
                    self._pluginUpdater.pluginUpdateDict(modname, plugin_init_update, plugin_resources_update, plugin_syntax_update, \
                                                        plugin_tabbed_indentation, os.path.join(_.path, modname, '__init__.py'), resourcesDirs, tabbed_modules)
            self.fillUpdatesList()

            if self._ui.listWidget.count() == 0:
                self._ui.label_2.setText('None of your plugins require updates at this time.')
            else:
                self._ui.label_2.setText('Tip: Update a single plugin by double-clicking!')
示例#38
0
    def _get_mouse_position ( self ):
        pos = QCursor.pos()

        return ( pos.x(), pos.y() )
示例#39
0
 def show_menu(self):
     self.popup(QCursor.pos())
     self.show()
示例#40
0
def toggleTabTabTab():
    if hiero.ui.tabtabtab.isHidden():
        hiero.ui.tabtabtab.showAt(QCursor.pos())
    else:
        hiero.ui.tabtabtab.hide()
示例#41
0
文件: widgets.py 项目: nb1987/rvac
	def showMenu(self):
		self.widget.right_clicked = True	# set the widget's right_clicked variable to True so that the focusOutEvent won't push anything to the undo stack as a consequence of right-clicking
		self.popup(QCursor.pos())
		self.widget.right_clicked = False	# immediately reset the widget's right_clicked variable back to False
 def _get_closest_editor(self):
     pos = QCursor.pos()
     key = lambda w: QtGui.QVector2D(pos - w.pos()).lengthSquared()
     all_widgets = self.get_dock_widgets()
     if all_widgets:
         return min(all_widgets, key=key)
示例#43
0
 def handleInspectorMenu(self, pos):
     menu = QMenu()
     menu.addAction('Add')
     menu.addAction('Delete')
     menu.exec_(QCursor.pos())
示例#44
0
文件: accd.py 项目: Sugz/Python
 def showMenu( self ):
     if QRect(0, 0, self.width(), 20).contains(self.mapFromGlobal(QCursor.pos())):
         self._accordianWidget.emitItemMenuRequested(self)
示例#45
0
 def handleInspectorMenu(self, pos):
     menu = QMenu()
     menu.addAction("Add")
     menu.addAction("Delete")
     menu.exec_(QCursor.pos())
示例#46
0
 def showMenu(self, reason):
     # show menu also on left click
     self.contextMenu().exec_(QCursor.pos())
示例#47
0
    def writeCalculixInputFile(self):
        print 'writeCalculixInputFile'
        self.Start = time.time()

        #dirName = self.form.lineEdit_outputDir.text()
        dirName = self.TempDir
        print 'CalculiX run directory: ', dirName
        self.femConsoleMessage("Check dependencies...")
        self.form.label_Time.setText('Time: {0:4.1f}: '.format(time.time() -
                                                               self.Start))
        MeshObject = None
        if FemGui.getActiveAnalysis():
            for i in FemGui.getActiveAnalysis().Member:
                if i.isDerivedFrom("Fem::FemMeshObject"):
                    MeshObject = i
        else:
            QtGui.QMessageBox.critical(None, "Missing prerequisit",
                                       "No active Analysis")
            return

        if not MeshObject:
            QtGui.QMessageBox.critical(None, "Missing prerequisit",
                                       "No mesh object in the Analysis")
            return

        MathObject = None
        for i in FemGui.getActiveAnalysis().Member:
            if i.isDerivedFrom("App::MaterialObjectPython"):
                MathObject = i
        if not MathObject:
            QtGui.QMessageBox.critical(None, "Missing prerequisit",
                                       "No material object in the Analysis")
            return
        matmap = MathObject.Material

        FixedObject = None
        for i in FemGui.getActiveAnalysis().Member:
            if i.isDerivedFrom("Fem::ConstraintFixed"):
                FixedObject = i
        if not FixedObject:
            QtGui.QMessageBox.critical(
                None, "Missing prerequisit",
                "No fixed-constraint nodes defined in the Analysis")
            return

        ForceObject = None
        for i in FemGui.getActiveAnalysis().Member:
            if i.isDerivedFrom("Fem::ConstraintForce"):
                ForceObject = i
        if not ForceObject:
            QtGui.QMessageBox.critical(
                None, "Missing prerequisit",
                "No force-constraint nodes defined in the Analysis")
            return

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        self.Basename = self.TempDir + '/' + MeshObject.Name
        filename = self.Basename + '.inp'

        self.femConsoleMessage(self.Basename)
        self.femConsoleMessage("Write mesh...")

        # write mesh
        MeshObject.FemMesh.writeABAQUS(filename)

        # reopen file with "append" and add the analysis definition
        inpfile = open(filename, 'a')

        self.femConsoleMessage("Write loads & Co...")

        # write fixed node set
        NodeSetName = FixedObject.Name
        inpfile.write(
            '\n\n\n\n***********************************************************\n'
        )
        inpfile.write('** node set for fixed constraint\n')
        inpfile.write('*NSET,NSET=' + NodeSetName + '\n')
        for o, f in FixedObject.References:
            fo = o.Shape.getElement(f)
            if fo.ShapeType == 'Face':
                FixedObjectType = 'AreaSupport'
                n = MeshObject.FemMesh.getNodesByFace(fo)
                for i in n:
                    inpfile.write(str(i) + ',\n')
            elif fo.ShapeType == 'Edge':
                FixedObjectType = 'LineSupport'
                print 'Line Supports are not yet implemented to export to CalculiX'
                # getNodesByEdge(fo) # not implemented yet
            elif fo.ShapeType == 'Vertex':
                FixedObjectType = 'PointSupport'
                print 'Point Supports are not yet implemented to export to CalculiX'

        # write load node set
        NodeSetNameForce = ForceObject.Name
        inpfile.write(
            '\n\n\n\n***********************************************************\n'
        )
        inpfile.write('** node set for load\n')
        inpfile.write('*NSET,NSET=' + NodeSetNameForce + '\n')
        NbrForceNods = 0
        for o, f in ForceObject.References:
            fo = o.Shape.getElement(f)
            if fo.ShapeType == 'Face':
                ForceObjectType = 'AreaLoad'
                n = MeshObject.FemMesh.getNodesByFace(fo)
                for i in n:
                    inpfile.write(str(i) + ',\n')
                    NbrForceNods = NbrForceNods + 1
            elif fo.ShapeType == 'Edge':
                ForceObjectType = 'LineLoad'
                print 'Line Loads are not yet implemented to export to CalculiX'
                # getNodesByEdge(fo) # not implemented yet
            elif fo.ShapeType == 'Vertex':
                ForceObjectType = 'PointLoad'
                print 'Point Loads are not yet implemented to export to CalculiX'

        # get material properties
        YM = FreeCAD.Units.Quantity(
            MathObject.Material['Mechanical_youngsmodulus'])
        if YM.Unit.Type == '':
            print 'Material "Mechanical_youngsmodulus" has no Unit, asuming kPa!'
            YM = FreeCAD.Units.Quantity(YM.Value, FreeCAD.Units.Unit('Pa'))
        else:
            print 'YM unit: ', YM.Unit.Type
        print 'YM = ', YM

        PR = float(MathObject.Material['FEM_poissonratio'])
        print 'PR = ', PR

        # write material properties
        inpfile.write(
            '\n\n\n\n***********************************************************\n'
        )
        inpfile.write('** material\n')
        inpfile.write('** unit is MPa = N/mm2\n')
        inpfile.write('*MATERIAL, Name=' + matmap['General_name'] + '\n')
        inpfile.write('*ELASTIC \n')
        inpfile.write('{0:.3f}, '.format(YM.Value * 1E-3))
        inpfile.write('{0:.3f}\n'.format(PR))
        inpfile.write('*SOLID SECTION, Elset=Eall, Material=' +
                      matmap['General_name'] + '\n')

        # write step beginn
        inpfile.write(
            '\n\n\n\n***********************************************************\n'
        )
        inpfile.write(
            '** one step is needed to calculate the mechanical analysis of FreeCAD\n'
        )
        inpfile.write(
            '** loads are applied quasi-static, means without involving the time dimension\n'
        )
        inpfile.write('*STEP\n')
        inpfile.write('*STATIC\n')

        # write constaints
        inpfile.write('\n\n** constaints\n')
        if FixedObjectType == 'AreaSupport':
            inpfile.write('*BOUNDARY\n')
            inpfile.write(NodeSetName + ',1,3,0.0\n')
        elif FixedObjectType == 'LineSupport':
            pass  # ToDo
        elif FixedObjectType == 'PointSupport':
            pass  # ToDo

        # write loads
        #inpfile.write('*DLOAD\n')
        #inpfile.write('Eall,NEWTON\n')
        inpfile.write('\n\n** loads\n')
        if ForceObjectType == 'AreaLoad':
            Force = ForceObject.Force / NbrForceNods
            vec = ForceObject.DirectionVector
            inpfile.write('** direction: ' + str(vec) + '\n')
            inpfile.write(
                '** concentrated load [N] distributed on the area of the given faces.\n'
            )
            inpfile.write('** ' + str(ForceObject.Force) + ' N / ' +
                          str(NbrForceNods) + ' Nodes = ' + str(Force) +
                          ' N on each node\n')
            inpfile.write('*CLOAD\n')
            inpfile.write(NodeSetNameForce + ',1,' + ` vec.x * Force ` + '\n')
            inpfile.write(NodeSetNameForce + ',2,' + ` vec.y * Force ` + '\n')
            inpfile.write(NodeSetNameForce + ',3,' + ` vec.z * Force ` + '\n')
        elif ForceObjectType == 'LineLoad':
            pass  # ToDo
        elif ForceObjectType == 'PointLoad':
            pass  # ToDo

        # write outputs, both are needed by FreeCAD
        inpfile.write('\n\n** outputs --> frd file\n')
        inpfile.write('*NODE FILE\n')
        inpfile.write('U\n')
        inpfile.write('*EL FILE\n')
        inpfile.write('S, E\n')
        inpfile.write('** outputs --> dat file\n')
        inpfile.write('*NODE PRINT , NSET=Nall \n')
        inpfile.write('U \n')
        inpfile.write('*EL PRINT , ELSET=Eall \n')
        inpfile.write('S \n')
        inpfile.write('\n\n')

        # write step end
        inpfile.write('*END STEP \n')

        # write some informations
        FcVersionInfo = FreeCAD.Version()
        inpfile.write(
            '\n\n\n\n***********************************************************\n'
        )
        inpfile.write('**\n')
        inpfile.write('**   CalculiX Inputfile\n')
        inpfile.write('**\n')
        inpfile.write('**   written by    --> FreeCAD ' + FcVersionInfo[0] +
                      '.' + FcVersionInfo[1] + '.' + FcVersionInfo[2] + '\n')
        inpfile.write('**   written on    --> ' + time.ctime() + '\n')
        inpfile.write('**   file name     --> ' +
                      os.path.basename(FreeCAD.ActiveDocument.FileName) + '\n')
        inpfile.write('**   analysis name --> ' +
                      FemGui.getActiveAnalysis().Name + '\n')
        inpfile.write('**\n')
        inpfile.write('**\n')
        inpfile.write('**   Units\n')
        inpfile.write('**\n')
        inpfile.write('**   Geometry (mesh data)        --> mm\n')
        inpfile.write("**   Materials (young's modulus) --> N/mm2 = MPa\n")
        inpfile.write('**   Loads (nodal loads)         --> N\n')
        inpfile.write('**\n')
        inpfile.write('**\n')

        inpfile.close()

        QApplication.restoreOverrideCursor()
示例#48
0
 def layout_list_contextMenu(self, pos):
     menu = QMenu()
     default_action = menu.addAction(self.tr("Reset Layout"))
     default_action.triggered.connect(self.on_default_layout)
     menu.exec_(QCursor.pos())
示例#49
0
    def loadContextMenu(self):

        pos = QCursor.pos()
        point = QtCore.QPoint(pos.x() + 10, pos.y())
        self.exec_(point)
示例#50
0
    def paint(self, painter, option, index):
        """
        Re-implementation of the paint method. 
        This will render a stream item that contains an icon, the name, 
        a description, the game being played, and a dropdown menu.
        """
        super(StreamItemDelegate, self).paint(painter, option, index)
        stream = index.data()

        if option.state & QStyle.State_MouseOver:
            painter.fillRect(option.rect, option.palette.color(QPalette.Highlight))
            painter.setPen(Qt.white)
        else:
            painter.setPen(Qt.black)

        # I'll have a rectangle pls.
        r = option.rect

        # Draw the Service icon (Twitch, etc)
        icon = get_service_icon(stream.service)
        icon_size = 16
        icon_offset = (r.height()/2) - (icon_size/2)
        if stream.status == 0: #offline
            icon.paint(painter, r.left()+10, r.top()+icon_offset, icon_size, icon_size, Qt.AlignLeft | Qt.AlignVCenter, mode=QIcon.Disabled) 
        else:
            icon.paint(painter, r.left()+10, r.top()+icon_offset, icon_size, icon_size, Qt.AlignLeft | Qt.AlignVCenter, mode=QIcon.Normal) 

        # Paint the stream name
        painter.drawText(r.left()+40, r.top()-8, r.width(), r.height(), Qt.AlignVCenter | Qt.AlignLeft, stream.name)

        # Paint the game name, if any.
        painter.save()
        name_len = painter.fontMetrics().width(stream.name)
        font = painter.font()
        font.setPixelSize(9)
        font.setItalic(True)
        painter.setFont(font)
        painter.setPen(QColor(*get_game_colour(stream.game)))
        # Position of the left edge + the length of the name text + the offset of the stream name + an additional offset for padding.
        painter.drawText((r.left()+name_len)+40, r.top()-8, r.width(), r.height(), Qt.AlignVCenter | Qt.AlignLeft, stream.game)
        painter.restore()

        # Paint a dropdown button for options.
        x1 = 50; y1 = 8; iw = 9; ih = 6; 
        orect = r.adjusted(name_len+x1, y1, -(r.width()-(name_len+x1+iw)), -(r.height()-(y1+ih))) # Rectangle to store the dropdown icon
        hrect = orect.adjusted(-4, -3, 6, 5) # Rectangle to hover within.
        hbg = orect.adjusted(-2, -1, 2, 1) # Rectangle to draw the rounded background in
        options_button = QStyleOptionButton()
        # Cursor must be translated to relative positioning via the parent widget, note that is this is not a widget.
        if hrect.contains(self.parent.mapFromGlobal(QCursor.pos())):
            # Hover event for the dropdown options button
            options_button.icon = self.icons["down_hover"]
            # Draw a background behind the icon
            painter.save()
            painter.setRenderHints(painter.Antialiasing | painter.HighQualityAntialiasing)
            painter.setPen(QPen(QColor(101, 99, 98)))
            painter.setBrush(QBrush(QColor(101, 99, 98)))
            painter.drawRoundRect(QRectF(hbg), 10.0, 5.0)
            painter.restore()
        else:
            options_button.icon = self.icons["down_default"]
        options_button.iconSize = QSize(iw, ih)
        options_button.rect = orect
        options_button.features = QStyleOptionButton.Flat
        # Paint a Push Button Control.
        QApplication.style().drawControl(QStyle.CE_PushButton, options_button, painter)
         
        # Paint the description/status?
        painter.save()
        if stream.status == 0: #offline
            painter.setPen(Qt.darkGray)
            painter.drawText(r.left()+40, r.top()+8, r.width(), r.height(), Qt.AlignVCenter | Qt.AlignLeft, "Offline")
        else:
            painter.setPen(Qt.darkGreen)
            painter.drawText(r.left()+40, r.top()+8, r.width(), r.height(), Qt.AlignVCenter | Qt.AlignLeft, stream.channel.status)
        painter.restore()
示例#51
0
 def showIndividualContextMenu(self, person):
     actionLookup = {}
     
     m = QMenu()
     actionLookup['Show Details'] = m.addAction('Show Details')
     # TODO: Add to / remove from path targets
     m.addSeparator()
     
     a = m.addMenu('Set A as')
     b = m.addMenu('Set B as')
     for label1 in AppState.ADDITION_ITERATOR_ORDER:
         a2 = a.addMenu(label1)
         b2 = b.addMenu(label1)
         for label2 in AppState.LEVEL_OPTION_ORDER:
             actionLookup[('Set A as',
                           self.additionIterators[label1],
                           AppState.LEVEL_OPTIONS[label2])] = a2.addAction(label2)
             actionLookup[('Set B as',
                           self.additionIterators[label1],
                           AppState.LEVEL_OPTIONS[label2])] = b2.addAction(label2)
     
     m.addSeparator()
     
     actionLookup['Trim Parents'] = m.addAction('Trim Parents')
     actionLookup['Trim Spouses'] = m.addAction('Trim Spouses')
     actionLookup['Trim Children'] = m.addAction('Trim Children')
     if not person in self.aSet and not person in self.bSet:
         actionLookup['Trim Parents'].setDisabled(True)
         actionLookup['Trim Spouses'].setDisabled(True)
         actionLookup['Trim Children'].setDisabled(True)
     
     m.addSeparator()
     
     for label1 in AppState.ADDITION_ITERATOR_ORDER:
         temp = m.addMenu('Expand '+label1)
         for label2 in AppState.LEVEL_OPTION_ORDER:
             actionLookup[('Expand',
                           self.additionIterators[label1],
                           AppState.LEVEL_OPTIONS[label2])] = temp.addAction(label2)
     
     choice = m.exec_(QCursor.pos())
     
     if choice != None:
         for menus,action in actionLookup.iteritems():
             if action == choice:
                 if menus == 'Show Details':
                     self.showIndividualDetails(person)
                 elif menus == 'Trim Parents':
                     self.snip(person, [self.ped.CHILD_TO_PARENT])
                 elif menus == 'Trim Spouses':
                     self.snip(person, [self.ped.HUSBAND_TO_WIFE,
                                        self.ped.WIFE_TO_HUSBAND])
                 elif menus == 'Trim Children':
                     self.snip(person, [self.ped.PARENT_TO_CHILD])
                 else:
                     assert isinstance(menus,tuple)
                     newSet = set(menus[1](person,level=menus[2]))
                     if menus[0] == 'Set A as':
                         historyID = self.addPedigree(newSet)
                         self.changePedigreeA(historyID)
                     elif menus[0] == 'Set B as':
                         historyID = self.addPedigree(newSet)
                         self.changePedigreeB(historyID)
                     elif menus[0] == 'Expand':
                         self.expand(person, newSet)
                 break
    def handleEvents(self, event, signals):
        att = self.axisOrder[self.findAxisIndex(event.x)]
        # context menu
        if event.contextRequested:
            contextMenu = QMenu(self)
            
            contextMenu.addAction(u'Select all')
            contextMenu.addAction(u'Select none')
            
            contextMenu.addSeparator()
            
            
            act = QAction(u'Hide Axis', self)
            contextMenu.addAction(act)
            if len(self.axisOrder) <= 1:
                act.setEnabled(False)
            
            axesMenu = QMenu(u'Show/Hide Axes', self)
            axesActions = QActionGroup(self)
            for a in self.axisOrder:
                act = QAction(a,self,checkable=True)
                if self.axes[a].visible:
                    act.toggle()
                if len(self.axisOrder) <= 1:
                    act.setEnabled(False)
                axesActions.addAction(act)
            for act in axesActions.actions():
                axesMenu.addAction(act)
            contextMenu.addMenu(axesMenu)
            
            contextMenu.addSeparator()
            
            contextMenu.addAction(u'Use as X axis')
            contextMenu.addAction(u'Use as Y axis')
            
            resultAction = contextMenu.exec_(QCursor.pos())
            
            if resultAction != None and resultAction != 0:
                # Select all
                if resultAction.text() == u'Select all':
                    self.app.intMan.newOperation(operation.ALL,att=att.dataAxis)
                
                # Select none
                if resultAction.text() == u'Select none':
                    self.app.intMan.newOperation(operation.NONE,att=att.dataAxis)
                
                # Hide axis
                if resultAction.text() == u'Hide Axis':
                    self.toggleVisible(att)
                
                # Toggle axis
                if resultAction.actionGroup() == axesActions:
                    self.toggleVisible(resultAction.text())

                # X axis
                if resultAction.text() == u'Use as X axis':
                    if self.app.currentYattribute != self.app.currentXattribute:
                        self.axes[self.app.currentXattribute].visAxis.handle.background.setAttribute('fill',self.normalHandleColor)
                        self.axes[self.app.currentXattribute].visAxis.handle.originalBackgroundColor = self.normalHandleColor
                    self.axes[att].visAxis.handle.background.setAttribute('fill',self.activeHandleColor)
                    self.axes[att].visAxis.handle.originalBackgroundColor = self.activeHandleColor
                    
                    self.app.notifyAxisChange(att,xAxis=True)
                
                # Y axis
                if resultAction.text() == u'Use as Y axis':
                    if self.app.currentXattribute != self.app.currentYattribute:
                        self.axes[self.app.currentYattribute].visAxis.handle.background.setAttribute('fill',self.normalHandleColor)
                        self.axes[self.app.currentYattribute].visAxis.handle.originalBackgroundColor = self.normalHandleColor
                    self.axes[att].visAxis.handle.background.setAttribute('fill',self.activeHandleColor)
                    self.axes[att].visAxis.handle.originalBackgroundColor = self.activeHandleColor
                    
                    self.app.notifyAxisChange(att,xAxis=False)
        
        #if linesMoved:
        #    self.highlightedLayer.refreshLines(self.app.highlightedRsNumbers)
        
        return signals
示例#53
0
 def _activate_traymenu(self, reason):
     if reason == QSystemTrayIcon.ActivationReason.Trigger:
         self.showNormal()
     else:
         self.trayIconMenu.activateWindow()
         self.trayIconMenu.popup(QCursor.pos())
示例#54
0
 def getMousePos(cls):
     pos = QCursor.pos()
     pos_map = Jaime.instance.view.mapFromGlobal(pos)
     return pos_map