Example #1
0
 def moveMouseFromCenter(self, imgView, coords, modifier=Qt.NoModifier):
     centerPoint = old_div(imgView.rect().bottomRight(), 2)
     point = QPoint(*coords) + centerPoint
     move = QMouseEvent(QEvent.MouseMove, point, Qt.NoButton, Qt.NoButton,
                        modifier)
     QApplication.sendEvent(imgView, move)
     QApplication.processEvents()
Example #2
0
    def fake_key_sequence(self, event_string):
        ''' Fake key sequence.'''
        event_list = event_string.split("-")

        if len(event_list) > 1:
            for widget in [self.buffer_widget.focusProxy()]:
                last_char = event_list[-1]
                last_key = last_char
                if len(last_char) == 1:
                    last_key = last_char.lower()

                modifiers = Qt.NoModifier

                for modifier in event_list[0:-1]:
                    if modifier == "C":
                        modifiers |= Qt.ControlModifier
                    elif modifier == "M":
                        modifiers |= Qt.AltModifier
                    elif modifier == "S":
                        modifiers |= Qt.ShiftModifier
                    elif modifier == "s":
                        modifiers |= Qt.MetaModifier

                QApplication.sendEvent(
                    widget,
                    QKeyEvent(QEvent.KeyPress, qt_key_dict[last_key],
                              modifiers, last_key))
def fake_key_event(event_string, app_buffer):
    # Init.
    text = event_string
    modifier = Qt.NoModifier

    # Get key text.
    if event_string in qt_text_dict:
        text = qt_text_dict[event_string]

    if event_string in ["TAB", "<backtab>"]:
        text = ""

    if event_string == "<backtab>":
        modifier = Qt.ShiftModifier

    if event_string.isupper():
        modifier = Qt.ShiftModifier

    print("Press: ", event_string)

    # NOTE: don't ignore text argument, otherwise QWebEngineView not respond key event.
    key_press = QKeyEvent(QEvent.KeyPress, qt_key_dict[event_string], modifier,
                          text)

    for widget in app_buffer.get_key_event_widgets():
        QApplication.sendEvent(widget, key_press)
Example #4
0
    def test_dirlist_users(self):
        tabs = self.form.tabs.tabs
        tabs.setCurrentIndex(USERS_TAB_INDEX)
        current_tab = tabs.widget(USERS_TAB_INDEX)

        self.assertEqual(len(Users.users), 1)

        edits = current_tab.findChildren(QLineEdit)
        self.assertEqual(len(edits), 2)

        add_button = current_tab.findChild(QPushButton)
        self.assertIsNotNone(add_button)
        self.assertEqual(add_button.text(), "Add")
        add_button.click()

        edits = current_tab.findChildren(QLineEdit)
        self.assertEqual(len(edits), 4)

        self.assertEqual(edits[0].getValue(), "guest")
        self.assertEqual(edits[1].getValue(), "guest")

        QTest.keyClicks(edits[2], "test_user")
        self.assertEqual(edits[2].getValue(), "test_user")
        QApplication.sendEvent(edits[2], QEvent(QEvent.FocusOut))

        QTest.keyClicks(edits[3], "test_password")
        self.assertEqual(edits[3].getValue(), "test_password")
        QApplication.sendEvent(edits[2], QEvent(QEvent.FocusOut))

        edits[2].setValue("test_user1")
        self.assertEqual(edits[2].getValue(), "test_user1")

        self.assertEqual(len(Users.users), 2)
Example #5
0
 def __smoothMove(self):
     """ 计时器溢出时进行平滑滚动 """
     totalDelta = 0
     # 计算所有未处理完事件的滚动距离,定时器每溢出一次就将步数-1
     for i in self.stepsLeftQueue:
         totalDelta += self.__subDelta(i[0], i[1])
         i[1] -= 1
     # 如果事件已处理完,就将其移出队列
     while self.stepsLeftQueue and self.stepsLeftQueue[0][1] == 0:
         self.stepsLeftQueue.popleft()
     # 构造滚轮事件
     e = QWheelEvent(self.lastWheelEvent.pos(),
                     self.lastWheelEvent.globalPos(),
                     self.lastWheelEvent.pos(),
                     self.lastWheelEvent.globalPos(),
                     round(totalDelta), Qt.Vertical,
                     self.lastWheelEvent.buttons(), Qt.NoModifier)
     """ e = QWheelEvent(self.lastWheelEvent.pos(),
                     self.lastWheelEvent.globalPos(),
                     QPoint(),
                     self.lastWheelEvent.angleDelta(),
                     round(totalDelta), Qt.Vertical,
                     self.lastWheelEvent.buttons(), Qt.NoModifier) """
     # 将构造出来的滚轮事件发送给app处理
     QApplication.sendEvent(self.verticalScrollBar(), e)
     # 如果队列已空,停止滚动
     if not self.stepsLeftQueue:
         self.smoothMoveTimer.stop()
Example #6
0
 def copyPath(self) -> None:
     """
     Копирование пути до изображения в буфер обмена.
     """
     clipboard = QApplication.clipboard()
     clipboard.setText(os.path.abspath(self.filename))
     QApplication.sendEvent(clipboard, QEvent(QEvent.Clipboard))
Example #7
0
    def send_key(self, args):
        print("Send key: %s" % args)
        (buffer_id, event_string) = args.split(":")

        if buffer_id in self.buffer_dict:
            QApplication.sendEvent(self.buffer_dict[buffer_id].buffer_widget,
                                   fake_key_event(event_string))
Example #8
0
 def showMaximized(self):
     self._root.showMaximized()
     # 强制取消hover状态
     QApplication.sendEvent(
         self.buttonNormal,
         QMouseEvent(QMouseEvent.Leave, QPointF(), Qt.LeftButton,
                     Qt.NoButton, Qt.NoModifier))
Example #9
0
    def fake_key_event(self, event_string):
        ''' Fake key event.'''
        # Init.
        text = event_string
        modifier = Qt.NoModifier

        # Get key text.
        if event_string in qt_text_dict:
            text = qt_text_dict[event_string]

        if event_string in ["TAB", "<backtab>"]:
            text = ""
            if event_string == "<backtab>":
                modifier = Qt.ShiftModifier
        elif event_string.isupper():
            modifier = Qt.ShiftModifier

        # print("Press: ", event_string)

        # NOTE: don't ignore text argument, otherwise QWebEngineView not respond key event.
        try:
            key_press = QKeyEvent(QEvent.KeyPress, qt_key_dict[event_string],
                                  modifier, text)
        except:
            key_press = QKeyEvent(QEvent.KeyPress, Qt.Key_unknown, modifier,
                                  text)

        for widget in self.get_key_event_widgets():
            QApplication.sendEvent(widget, key_press)

        self.fake_key_event_filter(event_string)
Example #10
0
    def test_dirlist_scan_paths(self):
        tabs = self.form.tabs.tabs
        tabs.setCurrentIndex(LOCAL_SCAN_PATHS_TAB_INDEX)
        current_tab = tabs.widget(LOCAL_SCAN_PATHS_TAB_INDEX)

        edits = current_tab.findChildren(QLineEdit)
        self.assertEqual(len(edits), 1)
        scan_edit = edits[0]
        self.assertIsNotNone(scan_edit)
        logging.debug(scan_edit.text())

        add_button = _find_button_by_text(current_tab, "Add")
        self.assertIsNotNone(add_button)

        edits = current_tab.findChildren(DirectoryLocal)
        self.assertEqual(len(edits), 1)

        add_button.click()

        edits = current_tab.findChildren(DirectoryLocal)
        self.assertEqual(len(edits), 2)

        dir_local: DirectoryLocal = edits[1]
        temp_path = "/tmp"
        dir_local.setValue(temp_path)
        self.assertEqual(dir_local.getValue(), temp_path)
        QApplication.sendEvent(dir_local, QEvent(QEvent.FocusOut))
Example #11
0
 def set_output(self, key_text):
     """ 更改按键输出的音符 """
     global keys, sig, flag, posi, sharpflag
     checks = (self.check1.isChecked(), self.check2.isChecked(),
               self.check3.isChecked(), self.check4.isChecked(),
               self.check5.isChecked(), self.check6.isChecked(),
               self.check7.isChecked())
     checktext = ['-1', '-1', '-1', '-1', '-1', '-1', '-1']
     for i in range(7):  # 检查哪些音符可能固定#号
         if checks[i]:
             checktext[i] = str(i + 1)
         else:
             checktext[i] = '-1'
     if key_text == '+':  # 判断按键
         if flag < 2:
             flag += 1
     elif key_text == '-':
         if flag > -2:
             flag -= 1
     elif key_text == '0':
         flag = 0
     elif key_text == '8':
         self.text.insertPlainText(' ')
     elif key_text == '9':
         if self.modeRadio.isChecked():
             pass
         else:
             if sharpflag == 0:  #设置#
                 sharpflag = 1
                 self.statusbar.setStyleSheet("background: yellow")
             else:
                 sharpflag = 0
                 self.statusbar.setStyleSheet(
                     "background: rgb(255,255,255)")
     elif key_text in ('.', '。'):
         back_key = QKeyEvent(QEvent.KeyPress, Qt.Key_Backspace,
                              Qt.NoModifier)
         QApplication.sendEvent(self.text, back_key)
     elif key_text in keys:
         if (self.modeRadio.isChecked()) and (key_text in checktext):
             key = '#' + key_text
         else:
             if sharpflag == 1:
                 key = '#' + key_text
             else:
                 key = key_text
         try:
             final_key = self.add_brace(key, flag)
             self.text.insertPlainText(final_key)
         except Exception:
             QMessageBox.warning(self, "提示:", "输入超出范围!!",
                                 QMessageBox.Cancel, QMessageBox.Cancel)
     else:
         # self.text.insertPlainText(key_text)
         return False
     self.text.setStyleSheet(bordercolor[flag + 2])
     # self.statusbar.showMessage('第%s行  第%s列   共%s行    当前输入模式:%s    # 输入:%s'
     #                            % (posi[0], posi[1], posi[2], sig[flag + 2], sharp[sharpflag]))
     return True
Example #12
0
 def wheelEvent(self, e):
     if self._no_scroll_v is True:
         if abs(e.angleDelta().x()) > abs(e.angleDelta().y()):
             QApplication.sendEvent(self.horizontalScrollBar(), e)
         else:
             e.ignore()  # let parents handle it
     else:
         super().wheelEvent(e)
Example #13
0
    def focus_widget(self, event=None):
        '''Focus buffer widget.'''
        if event is None:
            event = QFocusEvent(QEvent.FocusIn, Qt.MouseFocusReason)
        QApplication.sendEvent(self.buffer_widget.focusProxy(), event)

        # Activate emacs window when call focus widget, avoid first char is not
        eval_in_emacs('eaf-activate-emacs-window', [])
Example #14
0
 def onAnimOutEnd(self):
     """离开动画结束
     """
     # 模拟点击外侧关闭
     QApplication.sendEvent(
         self,
         QMouseEvent(QMouseEvent.MouseButtonPress, QPointF(-1, -1),
                     Qt.LeftButton, Qt.NoButton, Qt.NoModifier))
Example #15
0
 def event(self, ev):
     if ev.type() == QEvent.KeyPress and any(ev.matches(key) for key in (
         QKeySequence.MoveToNextLine, QKeySequence.SelectNextLine,
         QKeySequence.MoveToPreviousLine, QKeySequence.SelectPreviousLine,
         QKeySequence.MoveToNextPage, QKeySequence.SelectNextPage,
         QKeySequence.MoveToPreviousPage, QKeySequence.SelectPreviousPage)):
         QApplication.sendEvent(self.parent().treeView, ev)
         return True
     return super(SearchLineEdit, self).event(ev)
Example #16
0
    def mouse_move(self, region):
        point_list = random_movement(region)

        for point in point_list:
            pos = QPoint(point[0], point[1])
            evt = QMouseEvent(QEvent.MouseMove, pos, Qt.NoButton,  Qt.NoButton, Qt.NoModifier)
            QApplication.sendEvent(self.web_page, evt)

        return point_list.pop()
Example #17
0
    def mouse_click(self, x, y):
        """ mouse click on given point(x, y) of web_page"""        
        self.logger.log("mouse clicking on point(%d, %d)" % (x,y), min_level=2)
        evt = QMouseEvent(QEvent.MouseButtonPress, QPoint(x,y), Qt.LeftButton, Qt.LeftButton, Qt.NoModifier)
        QApplication.sendEvent(self.web_page, evt)
        evt = QMouseEvent(QEvent.MouseButtonRelease, QPoint(x,y), Qt.LeftButton, Qt.LeftButton, Qt.NoModifier)
        QApplication.sendEvent(self.web_page, evt)

        self.store_har_timing("_onMouseClicked")
Example #18
0
 def eventFilter(self, obj, e: QEvent):
     """ 过滤事件 """
     if obj == self:
         if e.type() == QEvent.Hide:
             # 隐藏按钮组时强行取消按钮的hover状态
             e = QEvent(QEvent.Leave)
             QApplication.sendEvent(self.playButton, e)
             QApplication.sendEvent(self.addToButton, e)
     return super().eventFilter(obj, e)
Example #19
0
	def eventFilter(self, obj, ev):
		if (obj is not self.edit
			or ev.type() not in (QEvent.KeyPress, QEvent.KeyRelease)
			or ev.key() not in (Qt.Key_Down, Qt.Key_Up, Qt.Key_PageUp, Qt.Key_PageDown)):

			return super(BaseFileChooser, self).eventFilter(obj, ev)

		QApplication.sendEvent(self.view, ev)
		return True
Example #20
0
	def eventFilter(self, obj, ev):
		if (obj is not self.edit
			or ev.type() not in (QEvent.KeyPress, QEvent.KeyRelease)
			or ev.key() not in (Qt.Key_Down, Qt.Key_Up, Qt.Key_PageUp, Qt.Key_PageDown)):

			return super(BaseFileChooser, self).eventFilter(obj, ev)

		QApplication.sendEvent(self.view, ev)
		return True
Example #21
0
    def send_mouse_event_to_buffer(self, buffer_id, view_width, view_height,
                                   view_image_width, view_image_height, event):
        print("Send mouse: %s %s" % (buffer_id, event))

        global emacs_xid

        if buffer_id in self.buffer_dict:
            if event.type() in [
                    QEvent.MouseButtonPress, QEvent.MouseButtonRelease,
                    QEvent.MouseMove, QEvent.MouseButtonDblClick
            ]:
                # Get view render coordinate.
                view_render_x = (view_width - view_image_width) / 2
                view_render_y = (view_height - view_image_height) / 2

                # Just send event if response in view image area.
                if (event.x() >= view_render_x
                    ) and (event.x() <= view_render_x + view_image_width) and (
                        event.y() >= view_render_y) and (
                            event.y() <= view_render_y + view_image_height):
                    view_sizes = list(
                        map(lambda v: (v.width, v.height),
                            self.view_dict.values()))

                    buffer_width = emacs_width
                    buffer_height = emacs_height

                    if len(view_sizes) > 0:
                        buffer_width, buffer_height = max(
                            view_sizes, key=lambda size: size[0] * size[1])

                    width_scale = view_width * 1.0 / buffer_width
                    height_scale = view_height * 1.0 / buffer_height
                    image_scale = 1.0
                    if width_scale < height_scale:
                        image_scale = width_scale
                    else:
                        image_scale = height_scale

                    new_event_x = (event.x() - view_render_x) / image_scale
                    new_event_y = (event.y() - view_render_y) / image_scale
                    new_event_pos = QPointF(new_event_x, new_event_y)

                    new_event = QMouseEvent(event.type(), new_event_pos,
                                            event.button(), event.buttons(),
                                            event.modifiers())

                    QApplication.sendEvent(
                        self.buffer_dict[buffer_id].buffer_widget, new_event)
                else:
                    print(
                        "Do not send event, because event out of view's response area"
                    )
            else:
                QApplication.sendEvent(
                    self.buffer_dict[buffer_id].buffer_widget, event)
Example #22
0
    def eventFilter(self, obj, event):
        if event.type() in [
                QEvent.KeyPress,
                QEvent.KeyRelease,
                QEvent.MouseButtonPress,
                QEvent.MouseButtonRelease,
                QEvent.MouseMove,
                QEvent.MouseButtonDblClick,
                QEvent.Wheel,
                QEvent.InputMethod,
                QEvent.InputMethodQuery,
                QEvent.ShortcutOverride,
                QEvent.ActivationChange,
                QEvent.Enter,
                QEvent.WindowActivate,
        ]:
            QApplication.sendEvent(self, event)

            if event.type() == QEvent.KeyPress and event.key(
            ) == QtCore.Qt.Key_Control:
                self.press_ctrl_flag = True
            elif event.type() == QEvent.KeyRelease and event.key(
            ) == QtCore.Qt.Key_Control:
                self.press_ctrl_flag = False

            global emacs_xwindow_id

            xlib_display = get_xlib_display()
            xwindow = xlib_display.create_resource_object(
                "window", emacs_xwindow_id)

            mask = []
            event_key = event.text()
            if event.modifiers(
            ) & QtCore.Qt.AltModifier == QtCore.Qt.AltModifier:
                mask.append("Alt")
            elif event.modifiers(
            ) & QtCore.Qt.ControlModifier == QtCore.Qt.ControlModifier:
                mask.append("Ctrl")
            elif event.modifiers(
            ) & QtCore.Qt.ShiftModifier == QtCore.Qt.ShiftModifier:
                mask.append("Shift")
            elif event.modifiers(
            ) & QtCore.Qt.MetaModifier == QtCore.Qt.MetaModifier:
                mask.append("Super")

            send_string(xwindow, event_key, mask,
                        event.type() == QEvent.KeyPress)

            xlib_display.sync()
        else:
            if event.type() not in [12, 77]:
                call_method("%s %s" % (event.type(), event))

        return False
Example #23
0
    def keyPressEvent(self, e):
        key = e.key()
        mod = e.modifiers()
        if key == Qt.Key_Down or key == Qt.Key_Up:
            if not mod:
                QApplication.sendEvent( self.parent(), e ) 
                return
            elif mod == Qt.AltModifier:
                self.showPopup()

        QComboBox.keyPressEvent(self, e)
Example #24
0
    def strokeMouse(
        self,
        imgView: QAbstractScrollArea,
        start: Union[QPoint, Iterable[int]],
        end: Union[QPoint, Iterable[int]],
        modifier: int = Qt.NoModifier,
        numSteps: int = 10,
    ) -> None:
        """Drag the mouse between 2 points.

        Args:
            imgView: View that will receive mouse events.
            start: Start coordinates, inclusive.
            end:  End coordinates, *also inclusive*.
            modifier: This modifier will be active when pressing, moving and releasing.
            numSteps: The number of mouse move events.

        See Also:
            :func:`strokeMouseFromCenter`.
        """
        if not isinstance(start, QPoint):
            start = QPoint(*start)
        if not isinstance(end, QPoint):
            end = QPoint(*end)

        # Note: Due to the implementation of volumina.EventSwitch.eventFilter(),
        #       mouse events intended for the ImageView MUST go through the viewport.

        # Move to start
        move = QMouseEvent(QEvent.MouseMove, start, Qt.NoButton, Qt.NoButton, modifier)
        QApplication.sendEvent(imgView.viewport(), move)

        # Press left button
        press = QMouseEvent(QEvent.MouseButtonPress, start, Qt.LeftButton, Qt.NoButton, modifier)
        QApplication.sendEvent(imgView.viewport(), press)

        # Move to end in several steps
        # numSteps = numSteps
        for i in range(numSteps):
            nextPoint = start + (end - start) * (old_div(float(i), numSteps))
            move = QMouseEvent(QEvent.MouseMove, nextPoint, Qt.NoButton, Qt.NoButton, modifier)
            QApplication.sendEvent(imgView.viewport(), move)

        # Move to end
        move = QMouseEvent(QEvent.MouseMove, end, Qt.NoButton, Qt.NoButton, modifier)
        QApplication.sendEvent(imgView.viewport(), move)

        # Release left button
        release = QMouseEvent(QEvent.MouseButtonRelease, end, Qt.LeftButton, Qt.NoButton, modifier)
        QApplication.sendEvent(imgView.viewport(), release)

        # Wait for the gui to catch up
        QApplication.processEvents()
        self.waitForViews([imgView])
Example #25
0
 def event(self, ev):
     if ev.type() == QEvent.KeyPress and any(
             ev.matches(key) for key in
         (QKeySequence.MoveToNextLine, QKeySequence.SelectNextLine,
          QKeySequence.MoveToPreviousLine, QKeySequence.SelectPreviousLine,
          QKeySequence.MoveToNextPage, QKeySequence.SelectNextPage,
          QKeySequence.MoveToPreviousPage,
          QKeySequence.SelectPreviousPage)):
         QApplication.sendEvent(self.parent().treeView, ev)
         return True
     return super(SearchLineEdit, self).event(ev)
Example #26
0
 def event(self, ev):
     if self._textedit:
         if ((ev.type() in (QEvent.MouseButtonPress, QEvent.MouseButtonRelease)
              and ev.button() == Qt.LeftButton)
             or (ev.type() == QEvent.MouseMove and ev.buttons() & Qt.LeftButton)):
             new = QMouseEvent(ev.type(), QPoint(0, ev.y()),
                 ev.button(), ev.buttons(), ev.modifiers())
             return QApplication.sendEvent(self._textedit.viewport(), new)
         elif ev.type() == QEvent.Wheel:
             return QApplication.sendEvent(self._textedit.viewport(), ev)
     return super(LineNumberArea, self).event(ev)
Example #27
0
    def keyPressEvent(self, e):
        key = e.key()
        mod = e.modifiers()
        if key == Qt.Key_Down or key == Qt.Key_Up:
            if not mod:
                QApplication.sendEvent(self.parent(), e)
                return
            elif mod == Qt.AltModifier:
                self.showPopup()

        QComboBox.keyPressEvent(self, e)
Example #28
0
    def send_event(self, evt, *, postpone=False):
        """Send the given event to the underlying widget.

        Args:
            postpone: Postpone the event to be handled later instead of
                      immediately. Using this might cause crashes in Qt.
        """
        recipient = self._event_target()
        if postpone:
            QApplication.postEvent(recipient, evt)
        else:
            QApplication.sendEvent(recipient, evt)
Example #29
0
 def set_output(self, key_text):
     """ 更改按键输出的音符 """
     global keys, sig, flag, posi
     if key_text == '+':
         if flag < 2:
             flag += 1
             self.status_flag.setText(sig[flag + 2])
             self.statusbar.showMessage(
                 '第%s行  第%s列   共%s行    当前输入模式'
                 ':%s' % (posi[0], posi[1], posi[2], sig[flag + 2]))
         return True
     elif key_text == '-':
         if flag > -2:
             flag -= 1
             self.status_flag.setText(sig[flag + 2])
             self.statusbar.showMessage(
                 '第%s行  第%s列   共%s行    当前输入模式'
                 ':%s' % (posi[0], posi[1], posi[2], sig[flag + 2]))
         return True
     elif key_text == '0':
         flag = 0
         self.status_flag.setText(' 0 ')
         self.statusbar.showMessage(
             '第%s行  第%s列   共%s行    当前输入模式:%s' %
             (posi[0], posi[1], posi[2], sig[flag + 2]))
         return True
     elif key_text == '8':
         self.text.insertPlainText(' ')
         return True
     elif key_text == '9':
         self.text.insertPlainText('#')
         return True
     elif key_text in ('.', '。'):
         back_key = QKeyEvent(QEvent.KeyPress, Qt.Key_Backspace,
                              Qt.NoModifier)
         QApplication.sendEvent(self.text, back_key)
         return True
     elif key_text in keys:
         p = keys.index(key_text)
         cursor = self.text.textCursor()
         cursor.movePosition(cursor.Left, cursor.KeepAnchor, 1)
         if cursor.selectedText() == '#':
             cursor.deleteChar()
             try:
                 self.text.insertPlainText(keys[p + 12 * flag + 1])  # 输入
             except Exception:
                 QMessageBox.warning(self, "提示:", "输入超出范围!!",
                                     QMessageBox.Cancel, QMessageBox.Cancel)
         else:
             self.text.insertPlainText(keys[p + 12 * flag])
         return True
     else:
         return False
Example #30
0
    def send_event(self, evt, *, postpone=False):
        """Send the given event to the underlying widget.

        Args:
            postpone: Postpone the event to be handled later instead of
                      immediately. Using this might cause crashes in Qt.
        """
        recipient = self._event_target()
        if postpone:
            QApplication.postEvent(recipient, evt)
        else:
            QApplication.sendEvent(recipient, evt)
Example #31
0
    def strokeMouseFromCenter(self,
                              imgView,
                              start,
                              end,
                              modifier=Qt.NoModifier,
                              numSteps=10):
        """
        Drag the mouse between two coordinates.
        A modifier can be specified that will be keep pressed
        default no modifier
        """

        centerPoint = old_div(imgView.rect().bottomRight(), 2)

        startPoint = QPoint(*start) + centerPoint
        endPoint = QPoint(*end) + centerPoint

        # Note: Due to the implementation of volumina.EventSwitch.eventFilter(),
        #       mouse events intended for the ImageView MUST go through the viewport.

        # Move to start
        move = QMouseEvent(QEvent.MouseMove, startPoint, Qt.NoButton,
                           Qt.NoButton, modifier)
        QApplication.sendEvent(imgView.viewport(), move)

        # Press left button
        press = QMouseEvent(QEvent.MouseButtonPress, startPoint, Qt.LeftButton,
                            Qt.NoButton, modifier)
        QApplication.sendEvent(imgView.viewport(), press)

        # Move to end in several steps
        #numSteps = numSteps
        for i in range(numSteps):
            nextPoint = startPoint + (endPoint - startPoint) * (old_div(
                float(i), numSteps))
            move = QMouseEvent(QEvent.MouseMove, nextPoint, Qt.NoButton,
                               Qt.NoButton, modifier)
            QApplication.sendEvent(imgView.viewport(), move)

        # Move to end
        move = QMouseEvent(QEvent.MouseMove, endPoint, Qt.NoButton,
                           Qt.NoButton, modifier)
        QApplication.sendEvent(imgView.viewport(), move)

        # Release left button
        release = QMouseEvent(QEvent.MouseButtonRelease, endPoint,
                              Qt.LeftButton, Qt.NoButton, modifier)
        QApplication.sendEvent(imgView.viewport(), release)

        # Wait for the gui to catch up
        QApplication.processEvents()
        self.waitForViews([imgView])
Example #32
0
 def mousePressEvent(self, e: QMouseEvent):
     """ 转发鼠标点击事件给目标小部件 """
     super().mousePressEvent(e)
     if not self.forwardTargetWidget:
         return
     e = QMouseEvent(QEvent.MouseButtonPress,
                     QPoint(e.pos().x() + self.x() - self.forwardTargetWidget.x(),
                            e.pos().y() + self.y() - self.forwardTargetWidget.y()),
                     e.globalPos(),
                     Qt.LeftButton,
                     Qt.LeftButton,
                     Qt.NoModifier)
     QApplication.sendEvent(self.forwardTargetWidget, e)
Example #33
0
    def eventFilter(self, obj, event):
        if event.type() in self.mouseEvents and self.isDescendant(
                obj,
                self.view().window()):
            w = QApplication.widgetAt(event.globalPos())
            if self.isDescendant(w, self.currDescriptor):
                localpos = w.mapFromGlobal(event.globalPos())
                newev = QMouseEvent(event.type(), localpos, event.screenPos(),
                                    event.button(), event.buttons(),
                                    event.modifiers())
                QApplication.sendEvent(w, newev)
                self.preventHide = True

        if event.type() in (QEvent.Close,
                            QEvent.Hide) and obj == self.view().window():
            self.closeDescriptor()

        return False
Example #34
0
    def eventFilter(self, object, event):
        if (event.type() == QEvent.Wheel and not self.__d_ignoreWheelEvent):

            we = QWheelEvent(event)

            pos = self.wheelRect().center()

            wheelEvent = QWheelEvent(pos, QWidget.mapToGlobal(self, pos),
                                     we.pixelDelta(), we.angleDelta(),
                                     we.buttons(), we.modifiers(), we.phase(),
                                     we.inverted(), we.source())

            self.__d_ignoreWheelEvent = True
            QApplication.sendEvent(self, wheelEvent)
            self.__d_ignoreWheelEvent = False

            return True

        return Qwt.QwtWheel.eventFilter(object, event)
Example #35
0
    def strokeMouseFromCenter(self, imgView, start, end, modifier = Qt.NoModifier,numSteps = 10):
        """
        Drag the mouse between two coordinates.
        A modifier can be specified that will be keep pressed
        default no modifier
        """



        centerPoint = old_div(imgView.rect().bottomRight(), 2)

        startPoint = QPoint(*start) + centerPoint
        endPoint = QPoint(*end) + centerPoint

        # Note: Due to the implementation of volumina.EventSwitch.eventFilter(),
        #       mouse events intended for the ImageView MUST go through the viewport.

        # Move to start
        move = QMouseEvent( QEvent.MouseMove, startPoint, Qt.NoButton, Qt.NoButton, modifier )
        QApplication.sendEvent(imgView.viewport(), move )

        # Press left button
        press = QMouseEvent( QEvent.MouseButtonPress, startPoint, Qt.LeftButton, Qt.NoButton, modifier)
        QApplication.sendEvent(imgView.viewport(), press )

        # Move to end in several steps
        #numSteps = numSteps
        for i in range(numSteps):
            nextPoint = startPoint + (endPoint - startPoint) * ( old_div(float(i), numSteps) )
            move = QMouseEvent( QEvent.MouseMove, nextPoint, Qt.NoButton, Qt.NoButton, modifier )
            QApplication.sendEvent(imgView.viewport(), move )

        # Move to end
        move = QMouseEvent( QEvent.MouseMove, endPoint, Qt.NoButton, Qt.NoButton, modifier )
        QApplication.sendEvent(imgView.viewport(), move )

        # Release left button
        release = QMouseEvent( QEvent.MouseButtonRelease, endPoint, Qt.LeftButton, Qt.NoButton, modifier )
        QApplication.sendEvent(imgView.viewport(), release )

        # Wait for the gui to catch up
        QApplication.processEvents()
        self.waitForViews([imgView])
Example #36
0
    def strokeMouse(
        self,
        imgView: QAbstractScrollArea,
        startPoint: Union[QPointF, QPoint, Iterable[numbers.Real]],
        endPoint: Union[QPointF, QPoint, Iterable[numbers.Real]],
        modifier: int = Qt.NoModifier,
        numSteps: int = 10,
    ) -> None:
        """Drag the mouse between 2 points.

        Args:
            imgView: View that will receive mouse events.
            startPoint: Start coordinates, inclusive.
            endPoint:  End coordinates, also inclusive.
            modifier: This modifier will be active when pressing, moving and releasing.
            numSteps: The number of mouse move events.

        See Also:
            :func:`strokeMouseFromCenter`.
        """
        startPoint = _asQPointF(startPoint)
        endPoint = _asQPointF(endPoint)

        # Note: Due to the implementation of volumina.EventSwitch.eventFilter(),
        #       mouse events intended for the ImageView MUST go through the viewport.

        # Move to start
        move = QMouseEvent(QEvent.MouseMove, startPoint, Qt.NoButton,
                           Qt.NoButton, modifier)
        QApplication.sendEvent(imgView.viewport(), move)

        # Press left button
        press = QMouseEvent(QEvent.MouseButtonPress, startPoint, Qt.LeftButton,
                            Qt.NoButton, modifier)
        QApplication.sendEvent(imgView.viewport(), press)

        # Move to end in several steps
        for i in range(1, numSteps + 1):
            a = i / numSteps
            nextPoint = (1 - a) * startPoint + a * endPoint
            move = QMouseEvent(QEvent.MouseMove, nextPoint, Qt.NoButton,
                               Qt.NoButton, modifier)
            QApplication.sendEvent(imgView.viewport(), move)

        # Release left button
        release = QMouseEvent(QEvent.MouseButtonRelease, endPoint,
                              Qt.LeftButton, Qt.NoButton, modifier)
        QApplication.sendEvent(imgView.viewport(), release)

        # Wait for the gui to catch up
        QApplication.processEvents()
        self.waitForViews([imgView])
Example #37
0
def fake_key_event(event_string, app_buffer):
    # Init.
    text = event_string
    modifier = Qt.NoModifier

    # Get key text.
    if event_string in qt_text_dict:
        text = qt_text_dict[event_string]

    if event_string in ["TAB", "<backtab>"]:
        text = ""

    if event_string == "<backtab>":
        modifier = Qt.ShiftModifier

    # NOTE: don't ignore text argument, otherwise QWebEngineView not respond key event.
    key_press = QKeyEvent(QEvent.KeyPress, qt_key_dict[event_string], modifier, text)

    for widget in app_buffer.get_key_event_widgets():
        QApplication.sendEvent(widget, key_press)
Example #38
0
    def closeSecondaryEvent(self, event):
        """Close the main window.
        """
        document = self.current_document()
        if document.isModifiedStrict():
            if self.ask_save_changes() == QDialog.Rejected:
                # Reject the event
                event.ignore()
                return

        old_scheme = document.scheme()

        # Set an empty scheme to clear the document
        document.setScheme(config.workflow_constructor(parent=self))

        QApplication.sendEvent(old_scheme, QEvent(QEvent.Close))

        old_scheme.deleteLater()

        config.save_config()

        geometry = self.saveGeometry()
        state = self.saveState(version=self.SETTINGS_VERSION)
        settings = QSettings()
        settings.beginGroup("mainwindow")
        settings.setValue("geometry", geometry)
        settings.setValue("state", state)
        settings.setValue("canvasdock/expanded", self.dock_widget.expanded())
        settings.setValue("scheme-margins-enabled",
                          self.scheme_margins_enabled)

        settings.setValue("last-scheme-dir", self.last_scheme_dir)
        settings.setValue("widgettoolbox/state",
                          self.widgets_tool_box.saveState())

        settings.setValue("quick-help/visible",
                          self.canvas_tool_dock.quickHelpVisible())

        settings.endGroup()

        event.accept()
Example #39
0
    def eventFilter(self, obj, event):
        if event.type() in [QEvent.KeyPress, QEvent.KeyRelease,
                            QEvent.MouseButtonPress, QEvent.MouseButtonRelease,
                            QEvent.MouseMove, QEvent.MouseButtonDblClick, QEvent.Wheel,
                            QEvent.InputMethod, QEvent.InputMethodQuery, QEvent.ShortcutOverride,
                            QEvent.ActivationChange, QEvent.Enter, QEvent.WindowActivate,
        ]:
            QApplication.sendEvent(self, event)

            if event.type() == QEvent.KeyPress and event.key() == QtCore.Qt.Key_Control:
                self.press_ctrl_flag = True
            elif event.type() == QEvent.KeyRelease and event.key() == QtCore.Qt.Key_Control:
                self.press_ctrl_flag = False

            global emacs_xwindow_id

            xlib_display = get_xlib_display()
            xwindow = xlib_display.create_resource_object("window", emacs_xwindow_id)

            mask = []
            event_key = event.text()
            if event.modifiers() & QtCore.Qt.AltModifier == QtCore.Qt.AltModifier:
                mask.append("Alt")
            elif event.modifiers() & QtCore.Qt.ControlModifier == QtCore.Qt.ControlModifier:
                mask.append("Ctrl")
            elif event.modifiers() & QtCore.Qt.ShiftModifier == QtCore.Qt.ShiftModifier:
                mask.append("Shift")
            elif event.modifiers() & QtCore.Qt.MetaModifier == QtCore.Qt.MetaModifier:
                mask.append("Super")

            send_string(xwindow, event_key, mask, event.type() == QEvent.KeyPress)

            xlib_display.sync()
        else:
            if event.type() not in [12, 77]:
                call_method("%s %s" % (event.type(), event))

        return False
Example #40
0
    def eventFilter(self, obj, event):
        if event.type() == QEvent.FocusOut:
            self.abort()
            if self._info_frame is not None:
                self._info_frame.close()
            return True
        elif event.type() == QEvent.KeyPress:
            if event.key() == Qt.Key_Escape:
                self.abort()
                event.accept()
                return True
            elif event.key() in (Qt.Key_Return, Qt.Key_Enter, Qt.Key_Tab):
                self.abort()
                self.insert_proposal()
                return True
            elif event.key() == Qt.Key_Up:
                if self._proposal_view.is_first_selected():
                    self._proposal_view.select_last()
                    return True
                return False
            elif event.key() == Qt.Key_Down:
                if self._proposal_view.is_last_selected():
                    self._proposal_view.select_first()
                    return True
                return False
            elif event.key() in (Qt.Key_Left, Qt.Key_Right, Qt.Key_Home,
                                 Qt.Key_End):
                self.abort()
            else:
                pass
            QApplication.sendEvent(self._editor, event)
            if self.isVisible():
                self.update_proposal()
            return True

        return False
Example #41
0
 def send(cls, handlerObject, func, *args):
     e = ThunkEvent( func, *args )
     QApplication.sendEvent(handlerObject, e)
Example #42
0
 def _doMouseClick(obj, pos):
     evt = QMouseEvent(QEvent.MouseButtonPress, pos, Qt.LeftButton, Qt.LeftButton, Qt.NoModifier)
     QApplication.sendEvent(obj, evt)
     evt = QMouseEvent(QEvent.MouseButtonRelease, pos, Qt.LeftButton, Qt.LeftButton, Qt.NoModifier)
     QApplication.sendEvent(obj, evt)
Example #43
0
 def moveMouseFromCenter(self, imgView, coords ,modifier =Qt.NoModifier ):
     centerPoint = old_div(imgView.rect().bottomRight(), 2)
     point = QPoint(*coords) + centerPoint
     move = QMouseEvent( QEvent.MouseMove, point, Qt.NoButton, Qt.NoButton, modifier  )
     QApplication.sendEvent(imgView, move )
     QApplication.processEvents()
Example #44
0
    def deliverEvent(self, event, texCoord):
        # Map the texture co-ordinate into "screen" co-ordinates.
        # Mouse move and release events can extend beyond the boundaries
        # of the scene, for "click and drag off-screen" operations.
        # Mouse press and double-click events need to be constrained.
        bounds = self.sceneRect()
        screenX = qRound(texCoord.x() * bounds.width())
        screenY = qRound((1.0 - texCoord.y()) * bounds.height())
        if event.type() in (QEvent.GraphicsSceneMousePress,
                            QEvent.GraphicsSceneMouseDoubleClick,
                            QEvent.MouseButtonPress,
                            QEvent.MouseButtonDblClick):
            if screenX < 0:
                screenX = 0
            elif screenX >= bounds.width():
                screenX = qRound(bounds.width() - 1)
            if screenY < 0:
                screenY = 0
            elif screenY >= bounds.height():
                screenY = qRound(bounds.height() - 1)
            self.pressedPos = QPoint(screenX, screenY)

        # Convert the event and deliver it to the scene.
        eventType = event.type()

        if eventType in (QEvent.GraphicsSceneMouseMove,
                         QEvent.GraphicsSceneMousePress,
                         QEvent.GraphicsSceneMouseRelease,
                         QEvent.GraphicsSceneMouseDoubleClick):
            pass
            #QGraphicsSceneMouseEvent *ev =
                #static_cast<QGraphicsSceneMouseEvent *>(event)
            #QGraphicsSceneMouseEvent e(ev->type())
            #e.setPos(QPointF(screenX, screenY))
            #e.setScenePos(QPointF(screenX + bounds.x(), screenY + bounds.y()))
            #e.setScreenPos(QPoint(screenX, screenY))
            #e.setButtonDownScreenPos(ev->button(), d->pressedPos)
            #e.setButtonDownScenePos
                #(ev->button(), QPointF(d->pressedPos.x() + bounds.x(),
                                      #d->pressedPos.y() + bounds.y()))
            #e.setButtons(ev->buttons())
            #e.setButton(ev->button())
            #e.setModifiers(ev->modifiers())
            #e.setAccepted(false)
            #QApplication::sendEvent(this, &e)

        elif eventType == QEvent.GraphicsSceneWheel:
            pass
            #QGraphicsSceneWheelEvent *ev =
                #static_cast<QGraphicsSceneWheelEvent *>(event)
            #QGraphicsSceneWheelEvent e(QEvent::GraphicsSceneWheel)
            #e.setPos(QPointF(screenX, screenY))
            #e.setScenePos(QPointF(screenX + bounds.x(), screenY + bounds.y()))
            #e.setScreenPos(QPoint(screenX, screenY))
            #e.setButtons(ev->buttons())
            #e.setModifiers(ev->modifiers())
            #e.setDelta(ev->delta())
            #e.setOrientation(ev->orientation())
            #e.setAccepted(false)
            #QApplication::sendEvent(this, &e)

        elif eventType in (QEvent.MouseButtonPress,
                           QEvent.MouseButtonRelease,
                           QEvent.MouseButtonDblClick,
                           QEvent.MouseMove):
            pass
            #QMouseEvent *ev = static_cast<QMouseEvent *>(event)
            #QEvent::Type type
            #if (ev->type() == QEvent::MouseButtonPress)
                #type = QEvent::GraphicsSceneMousePress
            #else if (ev->type() == QEvent::MouseButtonRelease)
                #type = QEvent::GraphicsSceneMouseRelease
            #else if (ev->type() == QEvent::MouseButtonDblClick)
                #type = QEvent::GraphicsSceneMouseDoubleClick
            #else
                #type = QEvent::GraphicsSceneMouseMove
            #QGraphicsSceneMouseEvent e(type)
            #e.setPos(QPointF(screenX, screenY))
            #e.setScenePos(QPointF(screenX + bounds.x(), screenY + bounds.y()))
            #e.setScreenPos(QPoint(screenX, screenY))
            #e.setButtonDownScreenPos(ev->button(), d->pressedPos)
            #e.setButtonDownScenePos
                #(ev->button(), QPointF(d->pressedPos.x() + bounds.x(),
                                      #d->pressedPos.y() + bounds.y()))
            #e.setButtons(ev->buttons())
            #e.setButton(ev->button())
            #e.setModifiers(ev->modifiers())
            #e.setAccepted(false)
            #QApplication::sendEvent(this, &e)

        elif eventType == QEvent.Wheel:
            pass
            #QWheelEvent *ev = static_cast<QWheelEvent *>(event)
            #QGraphicsSceneWheelEvent e(QEvent::GraphicsSceneWheel)
            #e.setPos(QPointF(screenX, screenY))
            #e.setScenePos(QPointF(screenX + bounds.x(), screenY + bounds.y()))
            #e.setScreenPos(QPoint(screenX, screenY))
            #e.setButtons(ev->buttons())
            #e.setModifiers(ev->modifiers())
            #e.setDelta(ev->delta())
            #e.setOrientation(ev->orientation())
            #e.setAccepted(false)
            #QApplication::sendEvent(this, &e)

        #else:
            # Send the event directly without any conversion.
            # Typically used for keyboard, focus, and enter/leave events.
            #QApplication.sendEvent(self, event)

        QApplication.sendEvent(self, event)