def keys(self, pattern, text, native=False, blur=False): """Simulate typing by focusing on elements that match the pattern and triggering key events. If native is True then will use GUI key event simulation, else JavaScript. If blur is True then will blur focus at the end of typing. Returns the number of elements matched. """ es = self.find(pattern) for e in es: if native: key_map = { '\t': Qt.Key_Tab, '\n': Qt.Key_Enter, 'DOWN': Qt.Key_Down, 'UP': Qt.Key_Up } self.click_by_gui_simulation(e) self.wait(0.1) for c in text: key = key_map.get(c, QKeySequence(c)[0]) press = QKeyEvent(QEvent.KeyPress, key, Qt.NoModifier) release = QKeyEvent(QEvent.KeyRelease, key, Qt.NoModifier) QApplication.postEvent(self, press) QApplication.postEvent(self, release) else: #e.evaluateJavaScript("this.focus()") #self.click_by_user_event_simulation(e) self.fill(pattern, text, es=[e]) for event_name in ('focus', 'keydown', 'change', 'keyup', 'keypress'): self.trigger_js_event(e, event_name) if blur: e.evaluateJavaScript("this.blur()") return len(es)
def test_enter_pressed(self): data = [] self.patch(self.console_widget, "_write_command", lambda: data.append(True)) event = QKeyEvent(QEvent.KeyPress, Qt.Key_Enter, Qt.NoModifier, "") self.console_widget.keyPressEvent(event) self.assertEqual(data, [True]) event = QKeyEvent(QEvent.KeyPress, Qt.Key_Return, Qt.NoModifier, "") self.console_widget.keyPressEvent(event) self.assertEqual(data, [True, True])
def eventFilter(self, obj, event): if event.type() == QEvent.FocusIn: if obj is self.ui.chatLogView: if event.reason() == Qt.ActiveWindowFocusReason: self.ui.chatInputEdit.setFocus() if event.type() == QEvent.KeyPress: if obj is self.ui.chatInputEdit: if event.key() in (Qt.Key_Enter, Qt.Key_Return): if event.modifiers() & Qt.ShiftModifier: pass elif event.modifiers() & Qt.ControlModifier: # QTextEdit inserts <br/> with Ctrl+Enter, and a new # <p> element with Shift+Enter. There seem to be some # rendering issues with <br/>, so convert all Ctrl+Enter # keys to Shift+Enter. mod = event.modifiers() & (~Qt.ControlModifier) mod = mod | Qt.ShiftModifier newEvent = QKeyEvent(event.type(), event.key(), mod, event.text(), event.isAutoRepeat(), event.count()) QApplication.sendEvent(self.ui.chatInputEdit, newEvent) return True else: self._onChatInputEnter() return True return False
def keyPressEvent(self, event): "Atiene el evento de pulsación de tecla." self._cambios_sin_guardar = True # Permite usar tab como seleccionador de la palabra actual # en el popup de autocompletado. if event.key() in [Qt.Key_Tab]: if self.completer and self.completer.popup().isVisible(): event.ignore() nuevo_evento = QKeyEvent(QKeyEvent.KeyPress, Qt.Key_Return, Qt.NoModifier) try: if self.autocomplete(nuevo_evento): return None except UnicodeEncodeError: pass return None if editor_base.EditorBase.keyPressEvent(self, event): return None # Elimina los pares de caracteres especiales si los encuentra if event.key() == Qt.Key_Backspace: self._eliminar_pares_de_caracteres() if self.autocomplete(event): return None return QTextEdit.keyPressEvent(self, event)
def test_home_pressed_with_shift(self): self.console_widget._write_command() self.console_widget._write_command() self.console_widget.textCursor().insertText('a = 5') event = QKeyEvent(QEvent.KeyPress, Qt.Key_Home, Qt.ShiftModifier, "") self.console_widget._home_pressed(event) text = self.console_widget.textCursor().selectedText() self.assertEqual(text, "a = 5")
def test_remove_tag_with_delete_key(self): tw = TagsWidget() QTest.keyClicks(tw.lineEdit, 'lourd') tw.addTag() tw.listWidget.setCurrentRow(0) tw.keyPressEvent( QKeyEvent(QEvent.KeyPress, Qt.Key_Delete, Qt.NoModifier)) self.assertEqual(tw.listWidget.count(), 0)
def test_step_space(self): """ Test step """ w = self.widget event = QKeyEvent( QEvent.KeyPress, Qt.Key_Space, Qt.KeyboardModifiers(0)) # test function not crashes when no data and learner w.keyPressEvent(event) self.send_signal("Data", self.iris) # test theta set after step if not set yet w.keyPressEvent(event) self.assertIsNotNone(w.learner.theta) # check theta is changing when step old_theta = np.copy(w.learner.theta) w.keyPressEvent(event) self.assertNotEqual(sum(old_theta - w.learner.theta), 0) # with linear regression self.send_signal("Data", self.housing) # test theta set after step if not set yet w.keyPressEvent(event) self.assertIsNotNone(w.learner.theta) # check theta is changing when step old_theta = np.copy(w.learner.theta) w.keyPressEvent(event) self.assertNotEqual(sum(old_theta - w.learner.theta), 0) old_theta = np.copy(w.learner.theta) # to cover else example and check not crashes event = QKeyEvent( QEvent.KeyPress, Qt.Key_Q, Qt.KeyboardModifiers(0)) w.keyPressEvent(event) # check nothing changes assert_array_equal(old_theta, w.learner.theta)
def test_home_pressed(self): self.console_widget._write_command() self.console_widget._write_command() self.console_widget.textCursor().insertText('a = 5') event = QKeyEvent(QEvent.KeyPress, Qt.Key_Home, Qt.NoModifier, "") self.console_widget._home_pressed(event) self.assertEqual( self.console_widget.textCursor().position(), self.console_widget.document().lastBlock().position() + len(self.console_widget.prompt))
def test_backspace(self): self.console_widget._write_command() self.console_widget._write_command() self.console_widget.textCursor().insertText('a = 5') self.console_widget.selectAll() text = self.console_widget.textCursor().selectedText()[:-1] self.console_widget.moveCursor(QTextCursor.End) event = QKeyEvent(QEvent.KeyPress, Qt.Key_Backspace, Qt.NoModifier, "") self.console_widget.keyPressEvent(event) self.console_widget.selectAll() text_after = self.console_widget.textCursor().selectedText() self.assertEqual(text, text_after)
def test_backspace_remove_selection(self): self.console_widget._write_command() self.console_widget._write_command() self.console_widget.textCursor().insertText("a = 5") self.console_widget.selectAll() text = self.console_widget.textCursor().selectedText()[:-2] self.console_widget.moveCursor(QTextCursor.End) self.console_widget.setCursorPosition(3, QTextCursor.KeepAnchor) event = QKeyEvent(QEvent.KeyPress, Qt.Key_Backspace, Qt.NoModifier, "") self.console_widget.keyPressEvent(event) self.console_widget.selectAll() text_after = self.console_widget.textCursor().selectedText() self.assertEqual(text, text_after)
def test_check_event_on_selection_all_selected_no_text(self): self.console_widget._write_command() self.console_widget._write_command() self.console_widget.textCursor().insertText('a = 5') self.console_widget.selectAll() text = self.console_widget.textCursor().selectedText() self.assertTrue(self.console_widget.textCursor().hasSelection()) event = QKeyEvent(QEvent.KeyPress, Qt.Key_A, Qt.NoModifier, "") self.console_widget.keyPressEvent(event) self.assertTrue(self.console_widget.textCursor().hasSelection()) self.console_widget.selectAll() text_after = self.console_widget.textCursor().selectedText() self.assertEqual(text, text_after)
def event(self, event): if (event.type() == QEvent.KeyPress) and (event.key() == Qt.Key_Tab): if self.completionType == QCompleter.InlineCompletion: eventTab = QKeyEvent(QEvent.KeyPress, Qt.Key_End, Qt.NoModifier) super(LineEditTabCompleter, self).event(eventTab) else: completion = self.completer.currentCompletion() completion += os.path.sep self.selectAll() self.insert(completion) self.completer.popup().hide() return True return super(LineEditTabCompleter, self).event(event)
def keyPressEvent(self, event): "Atiene el evento de pulsación de tecla." self._cambios_sin_guardar = True # Permite usar tab como seleccionador de la palabra actual # en el popup de autocompletado. if event.key() in [Qt.Key_Tab]: if self.completer and self.completer.popup().isVisible(): event.ignore() nuevo_evento = QKeyEvent(QKeyEvent.KeyPress, Qt.Key_Return, Qt.NoModifier) try: if self.autocomplete(nuevo_evento): return None except UnicodeEncodeError: pass return None if editor_base.EditorBase.keyPressEvent(self, event): return None # Elimina los pares de caracteres especiales si los encuentra if event.key() == Qt.Key_Backspace: self._eliminar_pares_de_caracteres() self._borrar_un_grupo_de_espacios(event) if self.autocomplete(event): return None if event.key() == Qt.Key_Return: cursor = self.textCursor() block = self.document().findBlockByNumber(cursor.blockNumber()) whitespace = re.match(r"(\s*)", unicode(block.text())).group(1) linea_anterior = str(block.text()[:]) cantidad_espacios = linea_anterior.count(' ') / 4 if linea_anterior[-1:] == ':': whitespace = ' ' * (cantidad_espacios + 1) else: whitespace = ' ' * (cantidad_espacios) QTextEdit.keyPressEvent(self, event) return self.insertPlainText(whitespace) return QTextEdit.keyPressEvent(self, event)
def eventFilter(self, editor, event): # check some key presses if event.type() == QEvent.KeyPress: # if we pressed return and aren't at the last column send a tab # if event.key() == Qt.Key_Return and not self.lastcolumn: # event.accept() # event = QKeyEvent(QEvent.KeyPress, Qt.Key_Tab, Qt.NoModifier) # if we pressed tab and are in the last column send a return if event.key() == Qt.Key_Tab and self.lastcolumn: event.accept() event = QKeyEvent(QEvent.KeyPress, Qt.Key_Return, Qt.NoModifier) # just pass the event up return QItemDelegate.eventFilter(self, editor, event)
def test_check_event_on_selection_last_block_selected(self): self.console_widget._write_command() self.console_widget._write_command() self.console_widget.textCursor().insertText('a = 5') self.console_widget.selectAll() text = self.console_widget.textCursor().selectedText()[:-2] + '2' self.console_widget.moveCursor(QTextCursor.End) self.console_widget.setCursorPosition(3, QTextCursor.KeepAnchor) self.assertTrue(self.console_widget.textCursor().hasSelection()) event = QKeyEvent(QEvent.KeyPress, Qt.Key_2, Qt.NoModifier, "2") self.console_widget.keyPressEvent(event) self.assertFalse(self.console_widget.textCursor().hasSelection()) self.console_widget.selectAll() text_after = self.console_widget.textCursor().selectedText() self.assertEqual(text, text_after)
def onExpandKeyEvent(self, keyEvent): """One of expand selection key events""" if self._start is None: currentBlockText = self._qpart.textCursor().block().text() line = self._qpart.cursorPosition[0] visibleColumn = self._realToVisibleColumn( currentBlockText, self._qpart.cursorPosition[1]) self._start = (line, visibleColumn) modifiersWithoutAltShift = keyEvent.modifiers() & ( ~(Qt.AltModifier | Qt.ShiftModifier)) newEvent = QKeyEvent(keyEvent.type(), keyEvent.key(), modifiersWithoutAltShift, keyEvent.text(), keyEvent.isAutoRepeat(), keyEvent.count()) self._qpart.cursorPositionChanged.disconnect(self._reset) self._qpart.selectionChanged.disconnect(self._reset) super(self._qpart.__class__, self._qpart).keyPressEvent(newEvent) self._qpart.cursorPositionChanged.connect(self._reset) self._qpart.selectionChanged.connect(self._reset)
def keyPressEvent(self, event): if self.autocomplete.active: if self.autocomplete.keyPressEvent(event): return elif self.calltip.active: if self.calltip.keyPressEvent(event): return m = event.modifiers() k = event.key() t = event.text() # Disable some shortcuts if self.disable_shortcuts and \ m & Qt.ControlModifier and k in [Qt.Key_A, Qt.Key_R, Qt.Key_C, Qt.Key_K, Qt.Key_X, Qt.Key_V, Qt.Key_Y, Qt.Key_Z]: new_ev = QKeyEvent(event.type(), k, m, t) event.ignore() QCoreApplication.postEvent(self.parent(), new_ev) return elif k == Qt.Key_Tab: if self.tab_pressed(): return elif k == Qt.Key_Backtab: if self.backtab_pressed(): return elif k == Qt.Key_Backspace: if self.backspace_pressed(): return elif k == Qt.Key_Period or \ (k == Qt.Key_Space and event.modifiers() == Qt.ControlModifier): QPlainTextEdit.keyPressEvent(self, event) self.autocomplete_pressed() return elif k in [Qt.Key_ParenLeft, Qt.Key_BraceLeft, Qt.Key_BracketLeft]: QPlainTextEdit.keyPressEvent(self, event) self.paren_opened(k) return QPlainTextEdit.keyPressEvent(self, event) if k == Qt.Key_Return or k == Qt.Key_Enter: self.after_return_pressed()
def _cut(self): event = QKeyEvent(QEvent.KeyPress, Qt.Key_X, Qt.ControlModifier, "x") self.keyPressEvent(event)
def keyPressEvent(self, event): # Permite usar tab como seleccionador de la palabra actual # en el popup de autocompletado. if event.key() in [Qt.Key_Tab]: if self.completer and self.completer.popup().isVisible(): event.ignore() nuevo_evento = QKeyEvent(QKeyEvent.KeyPress, Qt.Key_Return, Qt.NoModifier) try: if self.autocomplete(nuevo_evento): return None except UnicodeEncodeError: pass return None if editor_base.EditorBase.keyPressEvent(self, event): return None textCursor = self.textCursor() # Permite mantener pulsada la tecla CTRL para copiar o pegar. if event.modifiers() & Qt.ControlModifier: # Ignorando pegar texto si cursor está en medio de consola. if textCursor.blockNumber() != self.document().blockCount() - 1: if event.key() == Qt.Key_V: textCursor = self._mover_cursor_al_final() return # Ignorando pegar texto si cursor está sobre el prompt de consola. elif textCursor.positionInBlock() < 2: if event.key() == Qt.Key_V: textCursor = self._mover_cursor_al_final() return return QTextEdit.keyPressEvent(self, event) # Ignorando la pulsación de tecla si está en medio de la consola. if textCursor.blockNumber() != self.document().blockCount() - 1: textCursor = self._mover_cursor_al_final() return # Ignora el evento si está sobre el cursor de la consola. if textCursor.positionInBlock() < 2: textCursor = self._mover_cursor_al_final() return if event.key() in [Qt.Key_Left, Qt.Key_Backspace]: if self.textCursor().positionInBlock() == 2: return # Elimina los pares de caracteres especiales si los encuentra if event.key() == Qt.Key_Backspace: self._eliminar_pares_de_caracteres() # navegar por el historial if event.key() == Qt.Key_Down: if self.historyIndex == len(self.history): self.historyIndex -= 1 try: if self.historyIndex > -1: self.historyIndex -= 1 self.recall_history() else: self.clearCurrentBlock() except: pass return None # navegar por el historial if event.key() == Qt.Key_Up: try: if len(self.history) - 1 > self.historyIndex: self.historyIndex += 1 self.recall_history() else: self.historyIndex = len(self.history) except: pass return None # ir al primer caracter del interprete cuando pulsa HOME if event.key() == Qt.Key_Home: blockLength = len(self.document().lastBlock().text()[2:]) lineLength = len(self.document().toPlainText()) position = lineLength - blockLength textCursor = self.textCursor() textCursor.setPosition(position) self.setTextCursor(textCursor) return None try: if self.autocomplete(event): return None except UnicodeEncodeError: pass if event.key() in [Qt.Key_Return, Qt.Key_Enter]: self.limpiar_consejo() # Limpiando consejo si existe line = self._get_entered_line() self.historyIndex = -1 if line == "clear": self.limpiar() return try: line[-1] self.haveLine = True if line[-1] in [':', ',', '[', '(']: self.multiline = True self.history.insert(0, line) except: self.haveLine = False # Cuando pulsa ENTER luego de haber hecho un texto multilinea y borrado todos los caracteres. if self.multiline and (not self.haveLine or self._ha_ingresado_solo_espacios(line)): # multi line done self.append('') # move down one line try: self.interpreter.runsource(self.command) except Exception, e: self.insertar_error_desde_exception(e) self.command = '' # clear command self.multiline = False # back to single line self.marker() # handle marker style return None if self.haveLine and self.multiline: # multi line command self.command += line + '\n' # + command and line self.append('') self.marker() return None # Permite escribir lineas terminas con '?' para consultar la documentacion # de manera similar a como lo hace ipython. if line.endswith('?'): line = 'print ' + line[:-1] + '.__doc__' if self.haveLine and not self.multiline: # one line command self.command = line # line is the command self.append('') # move down one line if '=' in line: primer_parte = line.split('=')[0] if self.interpreter.es_metodo(primer_parte): print "ES METOPDO" self.insertar_error("No puedes sobre-escribir un metodo, lo siento.") self.command = '' # clear command self.marker() # handle marker style return None try: self.interpreter.runsource(self.command) except Exception, e: self.insertar_error_desde_exception(e) self.command = '' # clear command self.marker() # handle marker style return None
if __name__ == "__main__": import sys app = QApplication(sys.argv) # create an app from PyQt4.QtGui import QWidget import pqIMC IMC = pqIMC.tricorder() IMC.mainWindow = QWidget() beep() noteEvent("about to call infoMsg") infoMsg("This is the message","Did you hear that beep?") noteEvent("about to call getStringMsg") (s, b) = getStringMsg("TITLE STRING", "label text") if b : print( "got "+s) else: print("cancel") (s, b) = getStringMsg("TITLE STRING", "what you should enter", "prepared") if b : print( "got "+s) else: print("cancel") noteEvent("Whatever...") #ew = QTextEdit() #(b,qs) = getFindMsg(ew) #print(b,qs) qsl = QStringList() qsl.append("ONE") qsl.append("TWO") (s, b) = getChoiceMsg("TITLE STRING", "label text",qsl) if b : print ("Choice "+unicode(s)) else: print ("Cancel "+unicode(s)) printKeyEvent( QKeyEvent(QEvent.KeyPress,43,Qt.AltModifier|Qt.ControlModifier) )
def tuple2keyevent(past_event): """Convert tuple into a QKeyEvent instance""" return QKeyEvent(*past_event)