我正在尝试使用PySide2,并通过一个菜单打开一个对话框。由于某种原因,该对话框在项目启动时立即打开,而不是等到我单击“新建项目”。我是PySide2和Qt的新手,所以我认为我只是缺少明显的东西,有什么想法吗?
import sys
from PySide2.QtWidgets import *
class mainWindow(QMainWindow):
def __init__(self, parent=None):
super(mainWindow, self).__init__(parent)
self.setWindowTitle("Main Window")
self.createMenus()
def createMenus(self):
menuBar = self.menuBar()
fileMenu = menuBar.addMenu('&File')
fileMenu.addAction("&New Project", self.newProject())
fileMenu.addAction("&Open Project")
fileMenu.addAction("&Save Project")
fileMenu.addAction("E&xit", QApplication.closeAllWindows)
def newProject(self):
newProjDialog = QDialog(self)
newProjDialog.setWindowTitle("Create New Project")
newProjDialog.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
mainWindow = mainWindow()
mainWindow.show()
sys.exit(app.exec_())
提前感谢!
我知道了。我是对的,这很愚蠢。我应该传递self.newProject而不是传递self.newProject()。更正后的代码为:
class mainWindow(QMainWindow):
def __init__(self, parent=None):
super(mainWindow, self).__init__(parent)
self.setWindowTitle("Main Window")
self.createMenus()
def createMenus(self):
menuBar = self.menuBar()
fileMenu = menuBar.addMenu('&File')
fileMenu.addAction("&New Project", self.newProject)
fileMenu.addAction("&Open Project")
fileMenu.addAction("&Save Project")
fileMenu.addAction("E&xit", QApplication.closeAllWindows)
def newProject(self):
print('In newProject')
newProjDialog = QDialog(self)
newProjDialog.setWindowTitle("Create New Project")
newProjDialog.open()
if __name__ == '__main__':
app = QApplication(sys.argv)
mainWindow = mainWindow()
mainWindow.show()
sys.exit(app.exec_())