Python PyQt5 中的 connect() 方法在哪里?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27382053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:44:09  来源:igfitidea点击:

Where is the connect() method in PyQt5?

pythonqtpyqtpyqt5

提问by Liam

I'm following Mark Summerfield's Rapid GUI Programming with Python and Qtwhich is using PyQt4. I'd prefer to be working with PyQt5, but I have both on my machine. I'm on the second exercise in the book, which is as follows:

我正在关注Rapid GUI Programming with Python and Qt使用 PyQt4 的Mark Summerfield 。我更喜欢使用 PyQt5,但我的机器上都有。我正在做书中的第二个练习,内容如下:

from __future__ import division
import sys
from math import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *


class Form(QDialog):

    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        self.browser = QTextBrowser()
        self.lineedit = QLineEdit("Type an expression and press Enter")
        self.lineedit.selectAll()
        layout = QVBoxLayout()
        layout.addWidget(self.browser)
        layout.addWidget(self.lineedit)
        self.setLayout(layout)
        self.lineedit.setFocus()
        # This line fails:
        self.connect(self.lineedit, SIGNAL("returnPressed()"), self.updateUi)
        self.setWindowTitle("Calculate")


    def updateUi(self):
        try:
            text = unicode(self.lineedit.text())
            self.browser.append("%s = <b>%s</b>" % (text, eval(text)))
        except:
            self.browser.append(
                    "<font color=red>%s is invalid!</font>" % text)


app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()

When I run the script with PyQt4 (and swapping PyQt5.QtWidgetswith PyQt4.QtGui) it runs fine, but with PyQt5 it fails with:

当我运行PyQt4的(和交换脚本PyQt5.QtWidgetsPyQt4.QtGui),它运行良好,但与PyQt5它失败:

Traceback (most recent call last):
  File "calculate.pyw", line 32, in <module>
    form = Form()
  File "calculate.pyw", line 19, in __init__
    self.connect(self.lineedit, SIGNAL("returnProcessed()"), self.updateUi)
AttributeError: 'Form' object has no attribute 'connect'

I did some digging but apparently there are no changes to connectso I thought this might be an inheritance issue, however when I run dir(QDialog)in both PyQt4 and PyQt5 connectonly appears in PyQt4 (outputs trimmed, full output further down):

我做了一些挖掘,但显然没有连接变化,所以我认为这可能是一个继承问题,但是当我dir(QDialog)在 PyQt4 和 PyQt5 中运行时connect只出现在 PyQt4 中(输出被修剪,完整输出进一步向下):

Python 3.4.1 (default, Aug 24 2014, 21:32:40)
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from PyQt5.QtWidgets import *
>>> dir(QDialog)
[..., 'colorCount', 'connectNotify', 'contentsMargins', ...]

Python 2.7.8 (default, Aug 24 2014, 21:26:19)
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from PyQt4.QtGui import *
>>> dir(QDialog)
[..., 'colorCount', 'connect', 'connectNotify', 'contentsMargins', ...]

The connectmethod is present in PyQt4:

connect方法存在于 PyQt4 中:

Python 2.7.8 (default, Aug 24 2014, 21:26:19)
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from PyQt4.QtGui import *
>>> dir(QDialog)
['Accepted', 'DialogCode', 'DrawChildren', 'DrawWindowBackground',
 'IgnoreMask', 'PaintDeviceMetric', 'PdmDepth', 'PdmDpiX', 'PdmDpiY',
 'PdmHeight', 'PdmHeightMM', 'PdmNumColors', 'PdmPhysicalDpiX',
 'PdmPhysicalDpiY', 'PdmWidth', 'PdmWidthMM', 'Rejected', 'RenderFlag',
 'RenderFlags', '__class__', '__delattr__', '__dict__', '__doc__',
 '__format__', '__getattr__', '__getattribute__', '__hash__', '__init__',
 '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
 '__setattr__', '__sizeof__', '__str__', '__subclasshook__',
 '__weakref__', 'accept', 'acceptDrops', 'accepted',
 'accessibleDescription', 'accessibleName', 'actionEvent', 'actions',
 'activateWindow', 'addAction', 'addActions', 'adjustSize',
 'autoFillBackground', 'backgroundRole', 'baseSize', 'blockSignals',
 'changeEvent', 'childAt', 'childEvent', 'children', 'childrenRect',
 'childrenRegion', 'clearFocus', 'clearMask', 'close', 'closeEvent',
 'colorCount', 'connect', 'connectNotify', 'contentsMargins',
 'contentsRect', 'contextMenuEvent', 'contextMenuPolicy', 'create',
 'cursor', 'customContextMenuRequested', 'customEvent', 'deleteLater',
 'depth', 'destroy', 'destroyed', 'devType', 'disconnect',
 'disconnectNotify', 'done', 'dragEnterEvent', 'dragLeaveEvent',
 'dragMoveEvent', 'dropEvent', 'dumpObjectInfo', 'dumpObjectTree',
 'dynamicPropertyNames', 'effectiveWinId', 'emit', 'enabledChange',
 'ensurePolished', 'enterEvent', 'event', 'eventFilter', 'exec_',
 'extension', 'find', 'findChild', 'findChildren', 'finished',
 'focusInEvent', 'focusNextChild', 'focusNextPrevChild', 'focusOutEvent',
 'focusPolicy', 'focusPreviousChild', 'focusProxy', 'focusWidget',
 'font', 'fontChange', 'fontInfo', 'fontMetrics', 'foregroundRole',
 'frameGeometry', 'frameSize', 'geometry', 'getContentsMargins',
 'grabGesture', 'grabKeyboard', 'grabMouse', 'grabShortcut',
 'graphicsEffect', 'graphicsProxyWidget', 'handle', 'hasFocus',
 'hasMouseTracking', 'height', 'heightForWidth', 'heightMM', 'hide',
 'hideEvent', 'inherits', 'inputContext', 'inputMethodEvent',
 'inputMethodHints', 'inputMethodQuery', 'insertAction', 'insertActions',
 'installEventFilter', 'isActiveWindow', 'isAncestorOf', 'isEnabled',
 'isEnabledTo', 'isEnabledToTLW', 'isFullScreen', 'isHidden',
 'isLeftToRight', 'isMaximized', 'isMinimized', 'isModal', 
 'isRightToLeft', 'isSizeGripEnabled', 'isTopLevel', 'isVisible',
 'isVisibleTo', 'isWidgetType', 'isWindow', 'isWindowModified',
 'keyPressEvent', 'keyReleaseEvent', 'keyboardGrabber', 'killTimer',
 'languageChange', 'layout', 'layoutDirection', 'leaveEvent', 'locale',
 'logicalDpiX', 'logicalDpiY', 'lower', 'mapFrom', 'mapFromGlobal',
 'mapFromParent', 'mapTo', 'mapToGlobal', 'mapToParent', 'mask',
 'maximumHeight', 'maximumSize', 'maximumWidth', 'metaObject', 'metric',
 'minimumHeight', 'minimumSize', 'minimumSizeHint', 'minimumWidth',
 'mouseDoubleClickEvent', 'mouseGrabber', 'mouseMoveEvent',
 'mousePressEvent', 'mouseReleaseEvent', 'move', 'moveEvent',
 'moveToThread', 'nativeParentWidget', 'nextInFocusChain',
 'normalGeometry', 'numColors', 'objectName', 'open', 'orientation',
 'overrideWindowFlags', 'overrideWindowState', 'paintEngine',
 'paintEvent', 'paintingActive', 'palette', 'paletteChange', 'parent',
 'parentWidget', 'physicalDpiX', 'physicalDpiY', 'pos',
 'previousInFocusChain', 'property', 'pyqtConfigure', 'raise_',
 'receivers', 'rect', 'reject', 'rejected', 'releaseKeyboard',
 'releaseMouse', 'releaseShortcut', 'removeAction', 'removeEventFilter',
 'render', 'repaint', 'resetInputContext', 'resize', 'resizeEvent',
 'restoreGeometry', 'result', 'saveGeometry', 'scroll', 'sender',
 'senderSignalIndex', 'setAcceptDrops', 'setAccessibleDescription',
 'setAccessibleName', 'setAttribute', 'setAutoFillBackground',
 'setBackgroundRole', 'setBaseSize', 'setContentsMargins',
 'setContextMenuPolicy', 'setCursor', 'setDisabled', 'setEnabled',
 'setExtension', 'setFixedHeight', 'setFixedSize', 'setFixedWidth',
 'setFocus', 'setFocusPolicy', 'setFocusProxy', 'setFont',
 'setForegroundRole', 'setGeometry', 'setGraphicsEffect', 'setHidden',
 'setInputContext', 'setInputMethodHints', 'setLayout',
 'setLayoutDirection', 'setLocale', 'setMask', 'setMaximumHeight',
 'setMaximumSize', 'setMaximumWidth', 'setMinimumHeight',
 'setMinimumSize', 'setMinimumWidth', 'setModal', 'setMouseTracking',
 'setObjectName', 'setOrientation', 'setPalette', 'setParent',
 'setProperty', 'setResult', 'setShortcutAutoRepeat',
 'setShortcutEnabled', 'setShown', 'setSizeGripEnabled', 
 'setSizeIncrement', 'setSizePolicy', 'setStatusTip', 'setStyle',
 'setStyleSheet', 'setTabOrder', 'setToolTip', 'setUpdatesEnabled',
 'setVisible', 'setWhatsThis', 'setWindowFilePath', 'setWindowFlags',
 'setWindowIcon', 'setWindowIconText', 'setWindowModality',
 'setWindowModified', 'setWindowOpacity', 'setWindowRole',
 'setWindowState', 'setWindowTitle', 'show', 'showEvent',
 'showExtension', 'showFullScreen', 'showMaximized', 'showMinimized',
 'showNormal', 'signalsBlocked', 'size', 'sizeHint', 'sizeIncrement',
 'sizePolicy', 'stackUnder', 'startTimer', 'staticMetaObject',
 'statusTip', 'style', 'styleSheet', 'tabletEvent', 'testAttribute',
 'thread', 'timerEvent', 'toolTip', 'topLevelWidget', 'tr', 'trUtf8',
 'underMouse', 'ungrabGesture', 'unsetCursor', 'unsetLayoutDirection',
 'unsetLocale', 'update', 'updateGeometry', 'updateMicroFocus',
 'updatesEnabled', 'visibleRegion', 'whatsThis', 'wheelEvent', 'width',
 'widthMM', 'winId', 'window', 'windowActivationChange',
 'windowFilePath', 'windowFlags', 'windowIcon', 'windowIconText',
 'windowModality', 'windowOpacity', 'windowRole', 'windowState',
 'windowTitle', 'windowType', 'x', 'y']

But not PyQt5:

但不是 PyQt5:

Python 3.4.1 (default, Aug 24 2014, 21:32:40)
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from PyQt5.QtWidgets import *
>>> dir(QDialog)
['Accepted', 'DialogCode', 'DrawChildren', 'DrawWindowBackground',
 'IgnoreMask', 'PaintDeviceMetric', 'PdmDepth', 'PdmDevicePixelRatio',
 'PdmDpiX', 'PdmDpiY', 'PdmHeight', 'PdmHeightMM', 'PdmNumColors',
 'PdmPhysicalDpiX', 'PdmPhysicalDpiY', 'PdmWidth', 'PdmWidthMM',
 'Rejected', 'RenderFlag', 'RenderFlags', '__class__', '__delattr__',
 '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__',
 '__getattr__', '__getattribute__', '__gt__', '__hash__', '__init__',
 '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__',
 '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__',
 '__subclasshook__', '__weakref__', 'accept', 'acceptDrops', 'accepted',
 'accessibleDescription', 'accessibleName', 'actionEvent', 'actions',
 'activateWindow', 'addAction', 'addActions', 'adjustSize',
 'autoFillBackground', 'backgroundRole', 'baseSize', 'blockSignals',
 'changeEvent', 'childAt', 'childEvent', 'children', 'childrenRect',
 'childrenRegion', 'clearFocus', 'clearMask', 'close', 'closeEvent',
 'colorCount', 'connectNotify', 'contentsMargins', 'contentsRect',
 'contextMenuEvent', 'contextMenuPolicy', 'create',
 'createWindowContainer', 'cursor', 'customContextMenuRequested',
 'customEvent', 'deleteLater', 'depth', 'destroy', 'destroyed',
 'devType', 'devicePixelRatio', 'disconnect', 'disconnectNotify', 'done',
 'dragEnterEvent', 'dragLeaveEvent', 'dragMoveEvent', 'dropEvent',
 'dumpObjectInfo', 'dumpObjectTree', 'dynamicPropertyNames',
 'effectiveWinId', 'ensurePolished', 'enterEvent', 'event',
 'eventFilter', 'exec', 'exec_', 'find', 'findChild', 'findChildren',
 'finished', 'focusInEvent', 'focusNextChild', 'focusNextPrevChild',
 'focusOutEvent', 'focusPolicy', 'focusPreviousChild', 'focusProxy',
 'focusWidget', 'font', 'fontInfo', 'fontMetrics', 'foregroundRole',
 'frameGeometry', 'frameSize', 'geometry', 'getContentsMargins', 'grab',
 'grabGesture', 'grabKeyboard', 'grabMouse', 'grabShortcut',
 'graphicsEffect', 'graphicsProxyWidget', 'hasFocus',
 'hasHeightForWidth', 'hasMouseTracking', 'height', 'heightForWidth',
 'heightMM', 'hide', 'hideEvent', 'inherits', 'initPainter',
 'inputMethodEvent', 'inputMethodHints', 'inputMethodQuery',
 'insertAction', 'insertActions', 'installEventFilter', 'isActiveWindow',
 'isAncestorOf', 'isEnabled', 'isEnabledTo', 'isFullScreen', 'isHidden',
 'isLeftToRight', 'isMaximized', 'isMinimized', 'isModal',
 'isRightToLeft', 'isSignalConnected', 'isSizeGripEnabled', 'isVisible',
 'isVisibleTo', 'isWidgetType', 'isWindow', 'isWindowModified',
 'isWindowType', 'keyPressEvent', 'keyReleaseEvent', 'keyboardGrabber',
 'killTimer', 'layout', 'layoutDirection', 'leaveEvent', 'locale',
 'logicalDpiX', 'logicalDpiY', 'lower', 'mapFrom', 'mapFromGlobal',
 'mapFromParent', 'mapTo', 'mapToGlobal', 'mapToParent', 'mask',
 'maximumHeight', 'maximumSize', 'maximumWidth', 'metaObject', 'metric',
 'minimumHeight', 'minimumSize', 'minimumSizeHint', 'minimumWidth',
 'mouseDoubleClickEvent', 'mouseGrabber', 'mouseMoveEvent',
 'mousePressEvent', 'mouseReleaseEvent', 'move', 'moveEvent',
 'moveToThread', 'nativeEvent', 'nativeParentWidget', 'nextInFocusChain',
 'normalGeometry', 'objectName', 'objectNameChanged', 'open',
 'overrideWindowFlags', 'overrideWindowState', 'paintEngine',
 'paintEvent', 'paintingActive', 'palette', 'parent', 'parentWidget',
 'physicalDpiX', 'physicalDpiY', 'pos', 'previousInFocusChain',
 'property', 'pyqtConfigure', 'raise_', 'receivers', 'rect',
 'redirected', 'reject', 'rejected', 'releaseKeyboard', 'releaseMouse',
 'releaseShortcut', 'removeAction', 'removeEventFilter', 'render',
 'repaint', 'resize', 'resizeEvent', 'restoreGeometry', 'result',
 'saveGeometry', 'scroll', 'sender', 'senderSignalIndex',
 'setAcceptDrops', 'setAccessibleDescription', 'setAccessibleName',
 'setAttribute', 'setAutoFillBackground', 'setBackgroundRole',
 'setBaseSize', 'setContentsMargins', 'setContextMenuPolicy',
 'setCursor', 'setDisabled', 'setEnabled', 'setFixedHeight',
 'setFixedSize', 'setFixedWidth', 'setFocus', 'setFocusPolicy',
 'setFocusProxy', 'setFont', 'setForegroundRole', 'setGeometry',
 'setGraphicsEffect', 'setHidden', 'setInputMethodHints', 'setLayout',
 'setLayoutDirection', 'setLocale', 'setMask', 'setMaximumHeight',
 'setMaximumSize', 'setMaximumWidth', 'setMinimumHeight',
 'setMinimumSize', 'setMinimumWidth', 'setModal', 'setMouseTracking',
 'setObjectName', 'setPalette', 'setParent', 'setProperty', 'setResult',
 'setShortcutAutoRepeat', 'setShortcutEnabled', 'setSizeGripEnabled',
 'setSizeIncrement', 'setSizePolicy', 'setStatusTip', 'setStyle',
 'setStyleSheet', 'setTabOrder', 'setToolTip', 'setToolTipDuration',
 'setUpdatesEnabled', 'setVisible', 'setWhatsThis', 'setWindowFilePath',
 'setWindowFlags', 'setWindowIcon', 'setWindowIconText',
 'setWindowModality', 'setWindowModified', 'setWindowOpacity',
 'setWindowRole', 'setWindowState', 'setWindowTitle', 'sharedPainter',
 'show', 'showEvent', 'showFullScreen', 'showMaximized', 'showMinimized',
 'showNormal', 'signalsBlocked', 'size', 'sizeHint', 'sizeIncrement',
 'sizePolicy', 'stackUnder', 'startTimer', 'staticMetaObject',
 'statusTip', 'style', 'styleSheet', 'tabletEvent', 'testAttribute',
 'thread', 'timerEvent', 'toolTip', 'toolTipDuration', 'tr',
 'underMouse', 'ungrabGesture', 'unsetCursor', 'unsetLayoutDirection',
 'unsetLocale', 'update', 'updateGeometry', 'updateMicroFocus',
 'updatesEnabled', 'visibleRegion', 'whatsThis', 'wheelEvent', 'width',
 'widthMM', 'winId', 'window', 'windowFilePath', 'windowFlags',
 'windowHandle', 'windowIcon', 'windowIconChanged', 'windowIconText',
 'windowIconTextChanged', 'windowModality', 'windowOpacity',
 'windowRole', 'windowState', 'windowTitle', 'windowTitleChanged',
 'windowType', 'x', 'y']

What am I missing?

我错过了什么?

采纳答案by user3419537

You are using old-style signals and slots which have not been implemented in PyQt5. Try using new-style signals and slots.

您正在使用PyQt5 中尚未实现的旧式信号和插槽。尝试使用新式的信号和插槽

self.lineedit.returnPressed.connect(self.updateUi)

回答by AlbanMar31

Another answer is to add keyPressEvent()method to capture keyboards events.

另一个答案是添加keyPressEvent()方法来捕获键盘事件。

It will call your updateUi() method when the correct key is pressed.

当按下正确的键时,它将调用您的 updateUi() 方法。

def keyPressEvent(self, event):
    key = event.key()
    if key == Qt.Key_Enter:
        #For Enter of keyboard number
        print("key Enter press")
        self.updateUi()
    if key == Qt.Key_Return:
        #For Enter of keyboard
        print("key Enter press")
        self.updateUi()