1

我正在尝试将 PyQT4 代码转换为 PyQt5,这需要新的连接信号样式。当我使用:

self.connect(okButton, SIGNAL("clicked()"),form, SLOT("accept()"))
self.connect(cancelButton, SIGNAL("clicked()"),form, SLOT("reject()"))

一切都按预期工作 - 通过单击确定或取消,对话窗口将关闭。使用新样式的sygnals(我想我做错了什么)

okButton.clicked.connect(self.accept)
cancelButton.clicked.connect(self.reject)

单击确定/取消后,主窗口将关闭,对话框将保留。这绝对不是应该发生的事情。

我究竟做错了什么?

import sys
from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QLabel, QHBoxLayout, QVBoxLayout, QGridLayout
# from PyQt4.QtCore import *
# from PyQt4.QtGui import *

class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        myButton = QPushButton("open window")
        self.myFirstLabel = QLabel("First Window")
        layout = QVBoxLayout()
        layout.addWidget(myButton)
        layout.addWidget(self.myFirstLabel)
        self.setLayout(layout)
        myButton.clicked.connect(self.openNewWindow)
        self.setWindowTitle("SecondWindowTest")

    def openNewWindow(self):
        myLabel = QLabel("Second Window")
        okButton = QPushButton("&OK")
        cancelButton = QPushButton("Cancel")
        buttonLayout = QHBoxLayout()
        buttonLayout.addStretch()
        buttonLayout.addWidget(okButton)
        buttonLayout.addWidget(cancelButton)
        layout = QGridLayout()
        layout.addWidget(myLabel, 0, 0)
        layout.addLayout(buttonLayout, 1, 1, 1, 2)
        form = QDialog()
        form.setLayout(layout)

        okButton.clicked.connect(self.accept)
        cancelButton.clicked.connect(self.reject)
        # self.connect(okButton, SIGNAL("clicked()"),form, SLOT("accept()"))
        # self.connect(cancelButton, SIGNAL("clicked()"),form, SLOT("reject()"))

        form.setWindowTitle("Second Window")
        if form.exec_():
            self.myFirstLabel.setText('OK was pressed')

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

1 回答 1

2

等效于以下连接:

self.connect(okButton, SIGNAL("clicked()"),form, SLOT("accept()"))
self.connect(cancelButton, SIGNAL("clicked()"),form, SLOT("reject()"))

新的连接方式是:

okButton.clicked.connect(form.accept)
cancelButton.clicked.connect(form.reject)
于 2017-08-13T23:41:07.250 回答