无法将按钮连接到PyQT中的事件

时间:2017-02-13 12:52:10

标签: python-3.x user-interface pyqt4

我一直在尝试将按钮连接到某个功能,但我收到以下错误:

QObject.connect(b1,SIGNAL("clicked()"),GetBestMatch)           
TypeError: arguments did not match any overloaded call:
  QObject.connect(QObject, SIGNAL(), QObject, SLOT(), Qt.ConnectionType=Qt.AutoConnection): argument 1 has unexpected type 'NoneType'
  QObject.connect(QObject, SIGNAL(), callable, Qt.ConnectionType=Qt.AutoConnection): argument 1 has unexpected type 'NoneType'
  QObject.connect(QObject, SIGNAL(), SLOT(), Qt.ConnectionType=Qt.AutoConnection): first argument of unbound method must have type 'QObject'

这是我写下来的连接代码,它给出了错误:

QObject.connect(b1,SIGNAL("clicked()"),GetBestMatch) 

我还尝试通过以下代码进行连接:

b1.clicked.connect(GetBestMatch)

并收到错误:

b1.clicked.connect(GetBestMatch)         
AttributeError: 'NoneType' object has no attribute 'clicked'

我不知道我做错了什么。

我可以使用标签和按钮创建网格,但不能将按钮连接到功能。这是GUI代码:

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
def MainWindow():
    app = QApplication(sys.argv)
    screen_resolution = app.desktop().screenGeometry()
    width, height = screen_resolution.width(), screen_resolution.height()
    win = QWidget()
    win.adjustSize()
    grid=QGridLayout()
    grid.setRowStretch(0, 1)
    grid.setRowStretch(1, 1)
    grid.setRowStretch(5, 1)
    for i in range(0,5):
        for j in range(0,4):
            if i==0 and j==2:
               l1=grid.addWidget(QLabel("Choose an option:"),i,j, 2, 2)
            if i==2 and j==1:
                b1=grid.addWidget(QPushButton("Get Best Match"),i,j)
            elif i==2 and j==2:
                b2=grid.addWidget(QPushButton("Button 2"),i,j)
            elif i==2 and j==3:
                b3=grid.addWidget(QPushButton("Button 3"),i,j)
    b5=grid.addWidget(QLabel(""),3,4) 
    b4=grid.addWidget(QPushButton("Button 4"),2,4)         
    win.setLayout(grid)
    win.setGeometry(100,100,width//2,height//2,)
    win.setWindowTitle("Information on all tracking buses")
    win.show()
    win.setStyleSheet("""
    .QPushButton {
    height: 30px ;
    width: 20px ; 
    }
    .QLabel {
    qproperty-alignment: AlignCenter;
    font-size:12pt
    }

    """)
    sys.exit(app.exec_())

def GetBestMatch():
    print ("HI")
if __name__ == '__main__':
    MainWindow()

布局完美无误地运行。你能帮帮我吗?

1 个答案:

答案 0 :(得分:1)

QLayout.addWidget不会返回任何内容: http://doc.qt.io/qt-5/qlayout.html#addWidget

所以当你这样做时

b1=grid.addWidget(QPushButton("Get Best Match"),i,j)

一切都很好,但由于b1None - 因为错误消息清楚地说明了。 所以你需要花两行:

b1 = QPushButton("Get Best Match")
grid.addWidget(b1, i, j)

然后你应该好。