當前位置: 首頁>>代碼示例>>Python>>正文


Python QLineEdit.installEventFilter方法代碼示例

本文整理匯總了Python中PyQt5.QtWidgets.QLineEdit.installEventFilter方法的典型用法代碼示例。如果您正苦於以下問題:Python QLineEdit.installEventFilter方法的具體用法?Python QLineEdit.installEventFilter怎麽用?Python QLineEdit.installEventFilter使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在PyQt5.QtWidgets.QLineEdit的用法示例。


在下文中一共展示了QLineEdit.installEventFilter方法的8個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: StatusBar

# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import installEventFilter [as 別名]
class StatusBar (QStatusBar):
	def __init__(self):
		super(StatusBar, self).__init__()

		self.__statusMessageLabel = QLabel(self)
		self.__statusDataLabel = QLabel(self)
		self.__commandLine = QLineEdit(self)

		self.addPermanentWidget(self.__statusMessageLabel, 1)
		self.addPermanentWidget(self.__commandLine, 1)
		self.addPermanentWidget(self.__statusDataLabel)

		self.__commandLine.hide()

	def setStatus(self, statusMessage, statusData, cursorPosition, cursorAnchor, eventFilter):
		commandMode = cursorPosition != -1
		self.__commandLine.setVisible(commandMode)
		self.__statusMessageLabel.setVisible(not commandMode)

		if commandMode:
			self.__commandLine.installEventFilter(eventFilter)
			self.__commandLine.setFocus()
			self.__commandLine.setText(statusMessage)
			self.__commandLine.setSelection(cursorPosition, cursorAnchor - cursorPosition)
		else:
			self.__statusMessageLabel.setText(statusMessage)

		self.__statusDataLabel.setText(statusData)
開發者ID:ahnan4arch,項目名稱:retext,代碼行數:30,代碼來源:fakevimeditor.py

示例2: _refresh_widgets_from_axistags

# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import installEventFilter [as 別名]
    def _refresh_widgets_from_axistags(self):
        axiskeys = [tag.key for tag in self.axistags]
        row_widgets = collections.OrderedDict()
        for key in axiskeys:
            tag_info = self.axistags[key]
            
            resolution_box = QDoubleSpinBox(parent=self)
            resolution_box.setRange(0.0, numpy.finfo(numpy.float32).max)
            resolution_box.setValue( tag_info.resolution )
            resolution_box.valueChanged.connect( self._update_axistags_from_widgets )
            resolution_box.installEventFilter(self)
            
            description_edit = QLineEdit(tag_info.description, parent=self)
            description_edit.textChanged.connect( self._update_axistags_from_widgets )
            description_edit.installEventFilter(self)            

            row_widgets[key] = RowWidgets( resolution_box, description_edit )

        # Clean up old widgets (if any)
        for row in range(self.rowCount()):
            for col in range(self.columnCount()):
                w = self.cellWidget( row, col )
                if w:
                    w.removeEventFilter(self)

        # Fill table with widgets
        self.setRowCount( len(row_widgets) )
        self.setVerticalHeaderLabels( list(row_widgets.keys()) )
        for row, widgets in enumerate(row_widgets.values()):
            self.setCellWidget( row, 0, widgets.resolution_box )
            self.setCellWidget( row, 1, widgets.description_edit )
開發者ID:DerThorsten,項目名稱:ilastik,代碼行數:33,代碼來源:axistagsEditorWidget.py

示例3: LoginWidget

# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import installEventFilter [as 別名]
class LoginWidget(QWidget):

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

        lay = QHBoxLayout(self)  # сразу подключаем лэйаут к виджету w

        self.loginEdit = QLineEdit(self)
        self.loginEdit.setPlaceholderText('Имя')
        self.loginEdit.installEventFilter(self) # делаем текущий виджет наблюдателем событий виджета loginWidget

        self.passwordEdit = QLineEdit(self)
        self.passwordEdit.setPlaceholderText('Пароль')
        self.passwordEdit.setEchoMode(QLineEdit.Password)
        self.passwordEdit.installEventFilter(self) # делаем текущий виджет наблюдателем событий виджета passwordEdit

        self.loginButton = QPushButton(self)
        self.loginButton.setText('Войти')
        self.loginButton.clicked.connect(self.login)  # подсоединяем 'слот' к 'сигналу'

        lay.addWidget(self.loginEdit)
        lay.addWidget(self.passwordEdit)
        lay.addWidget(self.loginButton)

    def login(self, *args):
        global w
        name = w.loginEdit.text()
        password = w.passwordEdit.text()

        if User.login(name, password):
            w = Table()
            w.show()

    def eventFilter(self, watched, event):
        #print('eventFilter: {} - {}'.format(watched, event))
        return super().eventFilter(watched, event)

    def keyPressEvent(self, event):
        if event.key() in (
                PyQt5.QtCore.Qt.Key_Enter,
                PyQt5.QtCore.Qt.Key_Return): # FIXME найти тип
            print('-- ENTER --')
            self.login()
開發者ID:aaveter,項目名稱:curs_2016_b,代碼行數:45,代碼來源:buh3.py

示例4: BaseFileChooser

# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import installEventFilter [as 別名]
class BaseFileChooser(QWidget, WidgetMixin):
	def __init__(self, **kwargs):
		super(BaseFileChooser, self).__init__(**kwargs)

		self.options = PropDict()

		# sub-widgets
		layout = QVBoxLayout()
		self.setLayout(layout)

		self.edit = QLineEdit()
		layout.addWidget(self.edit)
		self.setFocusProxy(self.edit)

		self.view = QTreeView()
		layout.addWidget(self.view)

		self.edit.installEventFilter(self)

		self.setWindowTitle(self.tr('File selector'))
		self.addCategory('filechooser')

	def setModel(self, model):
		self.view.setModel(model)

	@Slot(str)
	def setRoot(self, path):
		raise NotImplementedError()

	def openFile(self, path):
		sendIntent(self, 'openEditor', path=path, reason='filechooser')

	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
開發者ID:hydrargyrum,項目名稱:eye,代碼行數:43,代碼來源:filechooser.py

示例5: HelpIndexWidget

# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import installEventFilter [as 別名]
class HelpIndexWidget(QWidget):
    """
    Class implementing a window for showing the QtHelp index.
    
    @signal linkActivated(QUrl) emitted when an index entry is activated
    @signal linksActivated(links, keyword) emitted when an index entry
        referencing multiple targets is activated
    @signal escapePressed() emitted when the ESC key was pressed
    """
    linkActivated = pyqtSignal(QUrl)
    linksActivated = pyqtSignal(dict, str)
    escapePressed = pyqtSignal()
    
    def __init__(self, engine, mainWindow, parent=None):
        """
        Constructor
        
        @param engine reference to the help engine (QHelpEngine)
        @param mainWindow reference to the main window object (QMainWindow)
        @param parent reference to the parent widget (QWidget)
        """
        super(HelpIndexWidget, self).__init__(parent)
        
        self.__engine = engine
        self.__mw = mainWindow
        
        self.__searchEdit = None
        self.__index = None
        
        self.__layout = QVBoxLayout(self)
        label = QLabel(self.tr("&Look for:"))
        self.__layout.addWidget(label)
        
        self.__searchEdit = QLineEdit()
        label.setBuddy(self.__searchEdit)
        self.__searchEdit.textChanged.connect(self.__filterIndices)
        self.__searchEdit.installEventFilter(self)
        self.__layout.addWidget(self.__searchEdit)
        
        self.__index = self.__engine.indexWidget()
        self.__index.installEventFilter(self)
        self.__engine.indexModel().indexCreationStarted.connect(
            self.__disableSearchEdit)
        self.__engine.indexModel().indexCreated.connect(
            self.__enableSearchEdit)
        self.__index.activated.connect(self.__activated)
        self.__searchEdit.returnPressed.connect(
            self.__index.activateCurrentItem)
        self.__layout.addWidget(self.__index)
        
        self.__index.viewport().installEventFilter(self)
    
    def __activated(self, idx):
        """
        Private slot to handle the activation of a keyword entry.
        
        @param idx index of the activated entry (QModelIndex)
        """
        model = self.__index.model()
        if model is not None:
            keyword = model.data(idx, Qt.DisplayRole)
            links = model.linksForKeyword(keyword)
            if len(links) == 1:
                self.linkActivated.emit(QUrl(links[list(links.keys())[0]]))
            else:
                self.linksActivated.emit(links, keyword)
    
    def __filterIndices(self, filter):
        """
        Private slot to filter the indices according to the given filter.
        
        @param filter filter to be used (string)
        """
        if '*' in filter:
            self.__index.filterIndices(filter, filter)
        else:
            self.__index.filterIndices(filter)
    
    def __enableSearchEdit(self):
        """
        Private slot to enable the search edit.
        """
        self.__searchEdit.setEnabled(True)
        self.__filterIndices(self.__searchEdit.text())
    
    def __disableSearchEdit(self):
        """
        Private slot to enable the search edit.
        """
        self.__searchEdit.setEnabled(False)
    
    def focusInEvent(self, evt):
        """
        Protected method handling focus in events.
        
        @param evt reference to the focus event object (QFocusEvent)
        """
        if evt.reason() != Qt.MouseFocusReason:
            self.__searchEdit.selectAll()
            self.__searchEdit.setFocus()
#.........這裏部分代碼省略.........
開發者ID:testmana2,項目名稱:test,代碼行數:103,代碼來源:HelpIndexWidget.py

示例6: ShortcutDialog

# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import installEventFilter [as 別名]
class ShortcutDialog(QDialog):
    """
    Dialog to set a shortcut for an action
    this class emit the follow signals:
        shortcutChanged(QKeySequence)
    """
    shortcutChanged = pyqtSignal(QKeySequence)

    def __init__(self, parent):
        super(ShortcutDialog, self).__init__()
        self.keys = 0
        #Keyword modifiers!
        self.keyword_modifiers = (Qt.Key_Control, Qt.Key_Meta, Qt.Key_Shift,
            Qt.Key_Alt, Qt.Key_Menu)
        #main layout
        main_vbox = QVBoxLayout(self)
        self.line_edit = QLineEdit()
        self.line_edit.setReadOnly(True)
        #layout for buttons
        buttons_layout = QHBoxLayout()
        ok_button = QPushButton(translations.TR_ACCEPT)
        cancel_button = QPushButton(translations.TR_CANCEL)
        #add widgets
        main_vbox.addWidget(self.line_edit)
        buttons_layout.addWidget(ok_button)
        buttons_layout.addWidget(cancel_button)
        main_vbox.addLayout(buttons_layout)
        self.line_edit.installEventFilter(self)
        #buttons signals
        ok_button.clicked['bool'].connect(self.save_shortcut)
        cancel_button.clicked['bool'].connect(self.close)

    def save_shortcut(self):
        """Save a new Shortcut"""
        self.hide()
        shortcut = QKeySequence(self.line_edit.text())
        self.shortcutChanged.emit(shortcut)

    def set_shortcut(self, txt):
        """Setup a shortcut"""
        self.line_edit.setText(txt)

    def eventFilter(self, watched, event):
        """Event Filter handling"""
        if event.type() == QEvent.KeyPress:
            self.keyPressEvent(event)
            return True

        return False

    def keyPressEvent(self, evt):
        """Key Press handling"""
        #modifier can not be used as shortcut
        if evt.key() in self.keyword_modifiers:
            return

        #save the key
        if evt.key() == Qt.Key_Backtab and evt.modifiers() & Qt.ShiftModifier:
            self.keys = Qt.Key_Tab
        else:
            self.keys = evt.key()

        if evt.modifiers() & Qt.ShiftModifier:
            self.keys += Qt.SHIFT
        if evt.modifiers() & Qt.ControlModifier:
            self.keys += Qt.CTRL
        if evt.modifiers() & Qt.AltModifier:
            self.keys += Qt.ALT
        if evt.modifiers() & Qt.MetaModifier:
            self.keys += Qt.META
        #set the keys
        self.set_shortcut(QKeySequence(self.keys).toString())
開發者ID:Salmista-94,項目名稱:Ninja_3.0_PyQt5,代碼行數:74,代碼來源:preferences_shortcuts.py

示例7: QtKeySequenceEdit

# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import installEventFilter [as 別名]
class QtKeySequenceEdit(QWidget):
    keySequenceChangedSignal = pyqtSignal(QKeySequence)
    def __init__(self,parent=None):
        super(QtKeySequenceEdit, self).__init__(parent)

        self.m_keySequence = QKeySequence()
        self.m_num = 0
        self.m_lineEdit = QLineEdit(self)
        layout = QHBoxLayout(self)
        layout.addWidget(self.m_lineEdit)
        layout.setContentsMargins(0, 0, 0, 0)
        self.m_lineEdit.installEventFilter(self)
        self.m_lineEdit.setReadOnly(True)
        self.m_lineEdit.setFocusProxy(self)
        self.setFocusPolicy(self.m_lineEdit.focusPolicy())
        self.setAttribute(Qt.WA_InputMethodEnabled)

    def eventFilter(self, o, e):
        if o == self.m_lineEdit and e.type() == QEvent.ContextMenu:
            c = e
            menu = self.m_lineEdit.createStandardContextMenu()
            actions = menu.actions()
            for action in actions:
                action.setShortcut(QKeySequence())
                actionString = action.text()
                pos = actionString.rfind('\t')
                if (pos > 0):
                    actionString = actionString[:pos]
                action.setText(actionString)

            actionBefore = None
            if (len(actions) > 0):
                actionBefore = actions[0]
            clearAction = QAction(self.tr("Clear Shortcut"), menu)
            menu.insertAction(actionBefore, clearAction)
            menu.insertSeparator(actionBefore)
            clearAction.setEnabled(not len(self.m_keySequence)<=0)
            clearAction.triggered.connect(self.slotClearShortcut)
            menu.exec(c.globalPos())
            e.accept()
            return True

        return super(QtKeySequenceEdit, self).eventFilter(o, e)

    def slotClearShortcut(self):
        if len(self.m_keySequence) <= 0:
            return
        self.setKeySequence(QKeySequence())
        self.keySequenceChangedSignal.emit(self.m_keySequence)

    def handleKeyEvent(self, e):
        nextKey = e.key()
        if (nextKey == Qt.Key_Control or nextKey == Qt.Key_Shift or
                nextKey == Qt.Key_Meta or nextKey == Qt.Key_Alt or
                nextKey == Qt.Key_Super_L or nextKey == Qt.Key_AltGr):
            return

        nextKey |= self.translateModifiers(e.modifiers(), e.text())
        k0 = 0
        k1 = 0
        k2 = 0
        k3 = 0
        l = len(self.m_keySequence)
        if l==1:
            k0 = self.m_keySequence[0]
        elif l==2:
            k0 = self.m_keySequence[0]
            k1 = self.m_keySequence[1]
        elif l==3:
            k0 = self.m_keySequence[0]
            k1 = self.m_keySequence[1]
            k2 = self.m_keySequence[2]
        elif l==4:
            k0 = self.m_keySequence[0]
            k1 = self.m_keySequence[1]
            k2 = self.m_keySequence[2]
            k3 = self.m_keySequence[3]
        if self.m_num==0:
            k0 = nextKey
            k1 = 0
            k2 = 0
            k3 = 0
        elif self.m_num==1:
            k1 = nextKey
            k2 = 0
            k3 = 0
        elif self.m_num==2:
            k2 = nextKey
            k3 = 0
        elif self.m_num==3:
            k3 = nextKey
        else:
            pass

        self.m_num += 1
        if (self.m_num > 3):
            self.m_num = 0
        self.m_keySequence = QKeySequence(k0, k1, k2, k3)
        self.m_lineEdit.setText(self.m_keySequence.toString(QKeySequence.NativeText))
        e.accept()
#.........這裏部分代碼省略.........
開發者ID:theall,項目名稱:Python-Tiled,代碼行數:103,代碼來源:qtpropertybrowserutils.py

示例8: EditableTabBar

# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import installEventFilter [as 別名]
class EditableTabBar(QTabBar):
    """ Inherits: QTabBar
        Implements editable label behaviour to tabs.
    """
    def __init__(self, parent=None):
        """ Constructor
            Params: QWidget parent -> object's parent
            Defines attributes:
                window as arg parent
                _editor as a QLineEdit object
        """
        super().__init__(parent)
        self.window = parent
        self._editor = QLineEdit(self)
        self._editor.setWindowFlags(Qt.Popup) #helps set location
        self._editor.setFocusProxy(self) #determines focus handling
        self._editor.editingFinished.connect(self.handleEditingFinished)
        self._editor.installEventFilter(self) #allows use of overloaded function eventFilter() to handle events

    def eventFilter(self, widget, event):
        """ Overloaded object method
            Params: QObject widget -> watched object (here: self)
                    QEvent event -> the event that is handled
            Return: True if the event is handled
                    Return value of QTabBar.eventFilter() if the event is not handled (bool)
            Determines editing is canceled if a click event is recorded outside of the _editor or if [esc] is pressed by hiding the _editor object.
            Else, the event is passed on to the parent class.
        """
        if ((event.type() == QEvent.MouseButtonPress and not self._editor.geometry().contains(event.globalPos())) or (event.type() == QEvent.KeyPress and event.key() == Qt.Key_Escape)):
            self._editor.hide()
            return True
        return QTabBar.eventFilter(self, widget, event)

    def mouseDoubleClickEvent(self, event):
        """ Overloaded object method
            Params: QEvent event -> the event that is handled
            Return: None
            Calls editTab() for the tab at which the double click event is recorded
        """
        index = self.tabAt(event.pos())
        if index >= 0 and self.window._styles[index]._user_style:
            self.editTab(index)

    def editTab(self, index):
        """ Object method
            Params: int index -> index of the tab to edit
            Return: None
            Sets the _editor's text, size and position to the tab label's and shows it.
        """
        rect = self.tabRect(index)
        self._editor.setFixedSize(rect.size())
        self._editor.move(self.window.mapToGlobal(rect.topLeft()))
        self._editor.setText(self.tabText(index))
        if not self._editor.isVisible():
            self._editor.show()

    def handleEditingFinished(self):
        """ Object method
            Params: None
            Return: None
            Hides the _editor and sets the entered string as the new tab label.
            Called at the automatic call of self._editor.editingFinished()
        """
        index = self.currentIndex()
        if index >= 0:
            self._editor.hide()
            new_name = self._editor.text()
            self.window._styles.rename(index, new_name)
            self.setTabText(index, new_name)
開發者ID:BAR-Rei,項目名稱:GooDoc,代碼行數:71,代碼來源:editable_tabs.py


注:本文中的PyQt5.QtWidgets.QLineEdit.installEventFilter方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。