so I'm pretty new to Python. And for the life of me can't figure out why the following code isn't working (I'm using PyQt5). I'm basically trying to have 2 widgets inside a stackedwidget so I can switch between them. And the button to switch from window 0 to window 1 would be in window 0 obviously. So I would need to be able to somehow reference the stackedwidget. But when I try to pass the stackedwidget as a reference, it complains that the variable is None, even when that shouldn't be the case.
from PyQt5.QtWidgets import QApplication, QWidget, QDesktopWidget, QGridLayout, QPushButton, QHBoxLayout, QVBoxLayout, QStackedWidget
from PyQt5.QtCore import QCoreApplication
class DeviceSelectionWindow(QWidget):
def __init__(self, mainWindow):
super().__init__()
self.initUI()
def initUI(self):
testB = QPushButton("test",self)
#------------------------------------------------------------
class ModeSelectionWindow(QWidget):
def __init__(self, mainWindow):
super().__init__()
self.mainWindow = mainWindow
self.initUI()
def initUI(self):
recordButton = QPushButton("Record tutorial")
watchButton = QPushButton("Watch tutorial")
recordButton.setFixedSize(200,100)
recordButton.setStyleSheet("font-size:30px")
watchButton.setFixedSize(200,100)
watchButton.setStyleSheet("font-size:30px")
recordButton.clicked.connect(self.mainWindow.setCurrentIndex(1))
#Add horizontal strech layout box (centered)
hbox = QHBoxLayout()
hbox.addWidget(recordButton)
hbox.addWidget(watchButton)
#Add vertical strech layout box (centered)
vbox = QVBoxLayout()
vbox.addLayout(hbox)
self.setLayout(vbox)
#------------------------------------------------------------
class MainWindow(QStackedWidget):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.initUI()
def initUI(self):
self.resize(1200,600)
self.centerWindow()
self.setWindowTitle("MultiPov Tutorial")
modeSelectionWindow = ModeSelectionWindow(self)
deviceSelectionWindow = DeviceSelectionWindow(self)
self.addWidget(modeSelectionWindow)
self.addWidget(deviceSelectionWindow)
self.show()
def centerWindow(self):
qr = self.frameGeometry()
cp = QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
#------------------------------------------------------------
if __name__=='__main__':
app = QApplication(sys.argv)
mainWindow = MainWindow()
sys.exit(app.exec_())
The connect
method takes a function name, you're doing a function call inside it which return None
.
recordButton.clicked.connect(self.mainWindow.setCurrentIndex(1))
One way to get around this is to write a method that does the work (change the index)
def setWindow1(self):
self.mainWindow.setCurrentIndex(1)
Then connect that method to the clicked
signal
recordButton.clicked.connect(self.setWindow1)
Or, use a lambda function and get it done in one line
recordButton.clicked.connect(lambda: self.mainWindow.setCurrentIndex(1))