ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-09-29 05:56:54  阅读:214  来源: 互联网

标签:pyqt5 python qt pyqt


我正在关注Mark Summerfield使用Python和Qt的快速GUI编程,它正在使用PyQt4.我更喜欢使用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_()

当我使用PyQt4运行脚本(并使用PyQt4.QtGui交换PyQt5.QtWidgets)时,它运行正常,但是使用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'

我做了一些挖掘,但显然是there are no changes to connect,所以我认为这可能是一个继承问题,但是当我在PyQt4和PyQt5中运行dir(QDialog)时,连接只出现在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', ...]

连接方法出现在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']

但不是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']

我错过了什么?

解决方法:

您正在使用具有not been implemented in PyQt5的旧式信号和插槽.请尝试使用new-style signals and slots.

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

标签:pyqt5,python,qt,pyqt
来源: https://codeday.me/bug/20190929/1830679.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有