可能是因为信号与槽的连接出现问题,或者新窗口的对象没有正确创建。以下是可能导致按钮单击连接在新窗口中不工作的几种情况以及相应的解决方法:
connect
函数,例如button.clicked.connect(self.open_new_window)
,其中button
是按钮对象,open_new_window
是新窗口的槽函数。QDialog
或QMainWindow
类创建新窗口对象,并使用show
或exec
函数将其显示出来。app.exec_()
函数,它将启动事件循环。下面是一个示例代码,演示如何在pyqt中使用按钮打开新窗口:
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QDialog
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.button = QPushButton("Open New Window", self)
self.button.clicked.connect(self.open_new_window)
def open_new_window(self):
new_window = QDialog(self)
new_window.setWindowTitle("New Window")
new_window.exec_()
if __name__ == '__main__':
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()
在这个示例中,我们创建了一个主窗口,并在主窗口中添加了一个按钮。按钮的单击事件会触发open_new_window
函数,该函数会创建并显示一个新的对话框窗口。确保你使用适当的窗口类来创建新窗口对象,例如QDialog
或QMainWindow
。
领取专属 10元无门槛券
手把手带您无忧上云