i'd like to learn PyQt by writing a simple game. the first widget would have buttons like "New game", "Quit", etc. i am having trouble understanding how to transition from that menu widget to a new one.
for instance, if i were to click New Game, how do i have a new widget appear that replaces the old one and asks for the user's name? the way i am approaching it now is something like
Form = QtGui.QWidget()
ui = uiMainMenu()
ui.setupUi(Form)
Form.show()
then once newGameButton is pressed it would go to a subroutine...
Form2 = QtGui.QWidget()
ui2 = uiNewGame()
ui2.setupUi(Form2)
Form2.show()
i'm not asking for all the code, just an explanation as to how i should be approaching the problem, because the code above ain't doing squat.
thanks!
if you want to switch between forms then you can use QStackedWidget.
Below you can find a working sample code:
import sys
from functools import partial
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class Form1(QWidget):
showForm2Signal = pyqtSignal()
def __init__(self, parent=None):
super(Form1, self).__init__(parent)
self.newGameButton = QPushButton("New Game", self)
self.quitButton = QPushButton("Quit", self)
layout = QVBoxLayout(self)
layout.addWidget(QLabel("<html>My Game<br>Start Page</html>"))
layout.addWidget(self.newGameButton)
layout.addWidget(self.quitButton)
self.newGameButton.clicked.connect(self.showForm2Signal.emit)
self.quitButton.clicked.connect(qApp.quit)
class Form2(QWidget):
showForm1Signal = pyqtSignal()
def __init__(self, parent=None):
super(Form2, self).__init__(parent)
self.backButton = QPushButton("Back", self)
layout = QVBoxLayout(self)
layout.addWidget(QLabel("New Game Started!"))
layout.addWidget(self.backButton)
self.backButton.clicked.connect(self.showForm1Signal.emit)
class MainWidget(QWidget):
def __init__(self, parent=None):
super(MainWidget, self).__init__(parent)
self.stack = QStackedWidget()
layout = QVBoxLayout(self)
layout.addWidget(self.stack)
self.form1 = Form1(self)
self.form2 = Form2(self)
self.stack.addWidget(self.form1)
self.stack.addWidget(self.form2)
self.form1.showForm2Signal.connect(partial(self.stack.setCurrentWidget,
self.form2))
self.form2.showForm1Signal.connect(partial(self.stack.setCurrentWidget,
self.form1))
self.stack.setCurrentWidget(self.form1)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MainWidget()
w.show()
app.exec_()
sys.exit()
If you only want to ask the name to the user then you can use a QDialog widget.
Related
I found some code on here that shows an example of how you can get the window to resize when the widget is hidden, and it works for me. Here is the code:
from PyQt4 import QtCore, QtGui
import sys
class MainWindow(QtGui.QWidget):
def __init__(self):
self.app = QtGui.QApplication(sys.argv)
super(MainWindow, self).__init__()
self.button = QtGui.QPushButton('Show/Hide')
self.button.setCheckable(True)
self.frame = QtGui.QFrame()
self.frame.setFixedHeight(100)
self.layout = layout = QtGui.QVBoxLayout()
layout2 = QtGui.QVBoxLayout()
self.setLayout(layout)
self.frame.setLayout(layout2)
layout.addWidget(self.button)
layout.addWidget(self.frame)
layout.addStretch(1)
layout2.addWidget(QtGui.QLabel('Yoyoyo'))
self.button.toggled.connect(self.clickAction)
def startup(self):
self.show()
sys.exit(self.app.exec_())
def clickAction(self):
checked = self.button.isChecked()
if checked:
self.frame.show()
else:
self.frame.hide()
QtCore.QTimer.singleShot(0, self.resizeMe)
def resizeMe(self):
self.resize(self.minimumSizeHint())
if __name__ == "__main__":
myApp = MainWindow()
myApp.startup()
I then tried to modify this to match my existing code by separating the mainWindow class and the widget class. Here is the code that does that.
from PySide import QtGui,QtCore
import sys
class MainWindow(QtGui.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.w = testW(self)
self.setCentralWidget(self.w)
self.show()
class testW(QtGui.QWidget):
def __init__(self,parent):
super(testW,self).__init__()
self.parent = parent
self.button = QtGui.QPushButton('Show/Hide')
self.button.setCheckable(True)
self.button.setChecked(True);
self.frame = QtGui.QFrame()
self.frame.setFixedHeight(100)
self.layout = layout = QtGui.QVBoxLayout()
layout2 = QtGui.QVBoxLayout()
self.setLayout(layout)
self.frame.setLayout(layout2)
layout.addWidget(self.button)
layout.addWidget(self.frame)
layout.addStretch(1)
layout2.addWidget(QtGui.QLabel('Yoyoyo'))
self.button.toggled.connect(self.clickAction)
def clickAction(self):
checked = self.button.isChecked()
if checked:
self.frame.show()
else:
self.frame.hide()
QtCore.QTimer.singleShot(0, self.resizeMe)
def resizeMe(self):
self.resize(self.minimumSizeHint())
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myApp = MainWindow()
sys.exit(app.exec_())
#time.sleep(1)
Running the first code does what I want it to. After I hide the widget, the window resizes to the correct size. The second implementation of the code does not shrink and expand the window when I hide and show the widget. Is this because the MainWindow is in a separate class?
Use size policies for your widgets. For your example you can change UI creation code as follows:
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.w = testW(self)
self.w.setSizePolicy(
QtWidgets.QSizePolicy.MinimumExpanding,
QtWidgets.QSizePolicy.MinimumExpanding
)
self.setCentralWidget(self.w)
self.show()
Please note new setSizePolicy call which say Qt layout engine how to change the size of your widget according to its content.
Unfortunately QMainWindow does not respect sizeHint automatically, but it is calculated properly, so you can adjustSize manually:
def clickAction(self):
checked = self.button.isChecked()
if checked:
self.frame.show()
else:
self.frame.hide()
QtCore.QTimer.singleShot(0, self.parent.adjustSize)
You do not need to resize your widget itself, because it will be resized according to the policy. Even sizeHint will be calculated automatically so you need only to call adjustSize of QMainWindow.
PS: I used PySide2 instead of PySide so the imports are different a little bit:
from PySide2 import QtWidgets, QtCore
I have a simple PyQt4 example.
When run, it displays a QMainWindow with a button.
If you click the button, then a second QMainWindow is created.
If you click it again, you get 2 second windows.
What is an elegant and simple way to prevent more than 1 second window in this example?
import sys
from PyQt4.QtGui import *
class win2(QMainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self,parent)
layout = QVBoxLayout()
label = QLabel(self)
label.setText('This is win2')
layout.addWidget(label)
self.adjustSize()
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
layout = QVBoxLayout()
button1 = QPushButton("win2", self)
layout.addWidget(button1)
button1.clicked.connect(self.showwin2)
def showwin2(self):
w2 = win2(self)
w2.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
mainWin = MainWindow()
mainWin.show()
sys.exit(app.exec_())
Your Function creates a new instance of the class win2 each time the button is pressed. To Supress this behavior only call the show and raise_ functions instead of creating a new instance.
I would create the class as follows, and only use the button to 'show' the window. Tested and works as intended. Also consider using self when assigning your variables so they can be accessed throughout the class instance.
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
layout = QVBoxLayout()
button1 = QPushButton("win2", self)
layout.addWidget(button1)
button1.clicked.connect(self.showwin2)
self.w2 = win2(self)
def showwin2(self):
self.w2.show()
self.w2.raise_()
So was creating a QGroupBox with a bunch of buttons, labels contained. Everything was working fine and now all of a sudden the buttons arent clickable. In fact nothing inside the groupbox is clickable. Any ideas? I've been pulling my hair out trying to see where i went wrong.
Have simplified the code down and tested it. No errors just cant click the button. Im wondering if its a parenting issue?
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class PxJob(QWidget):
def __init__(self, parent, geo, title):
super(PxJob, self).__init__(parent)
frame = QGroupBox(parent)
frame.setGeometry(geo)
frame.setTitle(title)
grid = QGridLayout()
frame.setLayout(grid)
butt = QPushButton('test')
butt.setCheckable(True)
grid.addWidget(butt)
class PxManager(QMainWindow):
def __init__(self, *args):
super(PxManager, self).__init__()
self.initUI()
def initUI(self):
# Main Layout
job = PxJob(self, QRect(10,60,830,120), 'Shot 02')
col = QVBoxLayout()
col.addWidget(job)
window = QWidget()
window.setLayout(col)
self.setCentralWidget(window)
self.setGeometry(300, 300, 850, 200)
self.setWindowTitle('Manager')
self.show()
def main():
app = QApplication(sys.argv)
ruc = PxManager()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
You need to add this line at the end of __init__ in PxJob:
self.setLayout(grid)
I have a Qwidget thats usually is displayed in a Qmainwindow.
Sometimes its unnecessary to use the whole mainwindow, because you only want to use functions from a certain Qwidget. If that's the case, I want a menubar in my widget.
I tried:
if parent == "self":
self.layout().addMenubar(self)
But using the code above the its just stops compiling without raising any error.
What Im doing wrong? Thanks!
OK, I can do !
You just add QtGui.QMenuBar(self) in your QWidget and implement just like QMainWindows.
Reference : Here
Example;
import sys
from PyQt4 import QtGui
class QTestWidget (QtGui.QWidget):
def __init__ (self):
super(QTestWidget, self).__init__()
self.myQMenuBar = QtGui.QMenuBar(self)
exitMenu = self.myQMenuBar.addMenu('File')
exitAction = QtGui.QAction('Exit', self)
exitAction.triggered.connect(QtGui.qApp.quit)
exitMenu.addAction(exitAction)
myQApplication = QtGui.QApplication(sys.argv)
myQTestWidget = QTestWidget()
myQTestWidget.show()
myQApplication.exec_()
Regards,
There is also a pretty clean way to combine QMainWindow with QWidget, using two classes:
import sys
from PyQt4 import QtCore, QtGui
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.win_widget = WinWidget(self)
widget = QtGui.QWidget()
layout = QtGui.QVBoxLayout(widget)
layout.addWidget(self.win_widget)
self.setCentralWidget(widget)
self.statusBar().showMessage('Ready')
self.toolbar = self.addToolBar('Exit')
exitAction = QtGui.QAction ('Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.triggered.connect(QtGui.qApp.quit)
self.toolbar = self.addToolBar('Exit')
self.toolbar.addAction(exitAction)
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
self.setGeometry(300, 300, 450, 250)
self.setWindowTitle('Test')
self.setWindowIcon (QtGui.QIcon('logo.png'))
self.show()
class WinWidget (QtGui.QWidget) :
def __init__(self, parent):
super (WinWidget , self).__init__(parent)
self.controls()
#self.__layout()
def controls(self):
self.qbtn = QtGui.QPushButton('Quit', self)
self.qbtn.setFixedSize (100,25)
self.qbtn.setToolTip ("quit")
self.qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit)
self.qbtn.move(50, 50)
def main():
app = QtGui.QApplication(sys.argv)
win = MainWindow()
win.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
This works :
def menu_bar (self) :
self.menuBar = QtGui.QMenuBar (self)
fileMenu = self.menuBar.addMenu ("File")
self.menuBar.show()
or already with actions :
def menu_bar (self) :
self.menuBar = QtGui.QMenuBar (self)
fileMenu = self.menuBar.addMenu ("File")
exitAction = QtGui.QAction(QtGui.QIcon('exit24.png'), 'Exit', self)
fileMenu.addAction(exitAction)
exitAction.triggered.connect(self.close)
exitAction.setShortcut('Ctrl+Q')
self.menuBar.show()
It will be a good idea to keep using QMainWindow since QMenuBar is designed to be used within it.
That said, I found this post helpful when I was also looking into doing same:
Qt QWidget add menubar
See if it's the solution that can help you. It helped me though
I need to add a new tab, but I am having problems. I want to add new tabs in the main window, and keep the methods of the class Editor(). I can do this without having to create the class Editor() but need it to be so. Sorry for my English.
This is my code:
from PyQt4 import QtGui
from PyQt4 import QtCore
class Main(QtGui.QMainWindow):
def __init__(self):
super(Main, self).__init__()
self.initUi()
def initUi(self):
self.setWindowTitle("Editor")
self.resize(640, 480)
self.edit = Editor()
newAc = QtGui.QAction('New', self)
newAc.setShortcut('Ctrl+N')
newAc.triggered.connect(self.new_)
menu = self.menuBar()
filemenu = menu.addMenu('&File')
filemenu.addAction(newAc)
self.tab = QtGui.QTabWidget(self)
self.setCentralWidget(self.tab)
class Editor(QtGui.QTextEdit):
def __init__(self, parent=None):
super(Editor, self).__init__(parent)
def new_(self):
tab = QtGui.QTextEdit(self.tab)
self.tab.addTab(tab, 'Untitled')
def main():
import sys
app = QtGui.QApplication(sys.argv)
w = Main()
w.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
If you want to have the same text on both (or more) tabs you can use the same Editor class, but if not, you need instantiate an Editor object for each tab.
Also your code have some problems:
1- You are handling the tabs inside Editor objects. Instead, you must handle tabs at Main level.
2- The "default" tab you're adding when you create the Main object do not have any related QTextEdit change:
self.tab = QtGui.QTabWidget(self)
self.setCentralWidget(self.tab) # <---- tab without QTextEdit
add this:
self.tab = QtGui.QTabWidget(self)
self.editor = Editor(self.tab) # editor receives self.tab widget as parent.
self.setCentralWidget(self.tab)
also you will need define Editor class before Main.
3- Main object don't have any method called new_, Editor does. So the line:
newAc.triggered.connect(self.new_)
it's wrong.
So your code might look like:
from PyQt4 import QtGui
from PyQt4 import QtCore
class Editor(QtGui.QTextEdit):
def __init__(self, parent=None):
super(Editor, self).__init__(parent)
class Main(QtGui.QMainWindow):
def __init__(self, parent=None):
super(Main, self).__init__(parent)
self.initUi()
def initUi(self):
self.setWindowTitle("Editor")
self.resize(640, 480)
newAc = QtGui.QAction('New', self)
newAc.setShortcut('Ctrl+N')
newAc.triggered.connect(self.new_)
menu = self.menuBar()
filemenu = menu.addMenu('&File')
filemenu.addAction(newAc)
self.tab = QtGui.QTabWidget(self)
self.setCentralWidget(self.tab)
self.tab.addTab(Editor(), "New Text")
def new_(self):
self.tab.addTab(Editor(), "New text")
def main():
import sys
app = QtGui.QApplication(sys.argv)
w = Main()
w.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()