Creating a button for PyQT window at each loop - python

class Test(QtGui.QMainWindow):
def __init__(self):
super(Test, self).__init__()
self.initUI()
def initUI(self):
YDrive = QtGui.QAction(QtGui.QIcon('y.gif'), 'Exit', self)
SDrive = QtGui.QAction('S', self)
GDrive = QtGui.QAction('G', self)
AddDrive = QtGui.QAction('+', self)
YDrive.triggered.connect(self.setYDir)
SDrive.triggered.connect(self.setSDir)
GDrive.triggered.connect(self.setGDir)
self.toolbar = self.addToolBar('Exit')
self.toolbar.addAction(YDrive)
self.toolbar.addAction(SDrive)
self.toolbar.addAction(GDrive)
self.toolbar.addAction(AddDrive)
#btn1 = QtGui.QPushButton("Button 1", self)
#btn1.move(30, 50)
#btn2 = QtGui.QPushButton("Button 2", self)
#btn2.move(150, 50)
#btn1.clicked.connect(self.buttonClicked)
#btn2.clicked.connect(self.buttonClicked)
self.setGeometry(300, 300, 250, 150)
self.center()
self.setWindowTitle('Message box')
self.show()
def setYDir(self):
myInputs[1] = "Y"
print "myInputs[1] CHANGED to Y"
myWorkDrive = "Y:\\HoC_Jobs\\"
shows = self.listDirs(myWorkDrive)
for elements in shows:
btn1 = QtGui.QPushButton(elements, self)
btn1.move(30, 50)
btn1.clicked.connect(self.buttonClicked)
What I'm trying to do in the last loop in setYDir is create a button for each element in the list shows. However, it doesn't seem to be working right. It does not update the buttons depending on thebutton I click in the toolbar. Any help?

Well, if you add components to a parent widget without using a layout and after you've called show on the parent, you'll have to show the children yourself.
Also, all your buttons are overlapping, so you'll only see the last one added. When posting source it's always good to strip it down to the minimum required to run it. In this case that would look something like this:
from PyQt4 import QtGui
import os
class Test(QtGui.QMainWindow):
def __init__(self):
super(Test, self).__init__()
self.initUI()
def initUI(self):
YDrive = QtGui.QAction("Y", self)
YDrive.triggered.connect(self.setYDir)
self.toolbar = self.addToolBar('Exit')
self.toolbar.addAction(YDrive)
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Message box')
self.show()
def buttonClicked(self):
print "clicked"
def setYDir(self):
myWorkDrive = "/tmp"
shows = os.listdir(myWorkDrive)
i = 0
for elements in shows:
btn1 = QtGui.QPushButton(elements, self)
btn1.move(30, 50 + i)
i += 30
btn1.clicked.connect(self.buttonClicked)
btn1.show()
self.resize(self.width(), 50 + i)
if __name__ == '__main__':
app = QtGui.QApplication([])
t = Test()
t.show()
app.exec_()

Related

how to properly remove qwidgets and update/reload that widget

Trying to remove a qwidget and replace it with another qwidget and then reload the layout the qwidget is a part of
I've already tried the update and removeWidget method, though i could've used it improperly
from PyQt5.Qt import *
import sys
validUser = False
app = None
class App(QMainWindow):
def __init__(self):
super().__init__()
screen = app.primaryScreen().size()
self.title = 'Restaurant Application'
width = screen.width()
height = screen.height()
self.left = 0
self.top = 0
self.width = width
self.height = height
self.setMouseTracking(True)
self.table_widget = MyTableWidget(self)
self.setCentralWidget(self.table_widget)
self.initUI()
self.show()
def initUI(self):
# window
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
# statusbar
self.statusBar().showMessage('Welcome to el restaurante')
def mousePressEvent(self, event):
print('Mouse coords: ( %d : %d )' % (event.x(), event.y()))
class MyTableWidget(QWidget):
def __init__(self, parent):
super(QWidget, self).__init__(parent)
self.layout = QVBoxLayout(self)
# Initialize tab screen
self.tabs = QTabWidget()
self.login = QWidget()
self.menu = QWidget()
self.checkOut = QWidget()
self.tabs.resize(500, 200)
# Add tabs
self.tabs.addTab(self.login, "Login")
self.tabs.addTab(self.menu, "Menu")
self.tabs.addTab(self.checkOut, "Check out")
# Create login tab
self.login.layout = QVBoxLayout(self)
self.menu.layout = QVBoxLayout(self)
# login text
self.loginPrompt = QLabel("Please provide a valid login")
self.loginPrompt.setFixedSize(315,30)
self.loginPromptFont = QFont("Times", 27, QFont.Bold)
self.loginPrompt.setFont(self.loginPromptFont)
self.login.layout.addWidget(self.loginPrompt)
self.login.setLayout(self.login.layout)
# Create textbox
self.loginTextbox = QLineEdit(self)
self.loginTextbox.returnPressed.connect(self.on_click_login)
self.loginTextbox.setFixedSize(170,20)
# Create a button in the window
self.loginButton = QPushButton('Login button', self)
self.loginButton.clicked.connect(self.on_click_login)
self.loginButton.setFixedSize(100,40)
self.login.layout.addWidget(self.loginTextbox,alignment=Qt.AlignCenter)
self.login.layout.addWidget(self.loginButton,alignment=Qt.AlignCenter)
#widget code i use to decide which widget to add
self.menuInvalidUserLogin = QLabel("Please login in to view")
self.menuValidUserLogin = QLabel("Here's the menu")
if(validUser):
self.menu.layout.addWidget(self.menuValidUserLogin)
else:
self.menu.layout.addWidget(self.menuInvalidUserLogin)
self.menu.setLayout(self.menu.layout)
# Add tabs to widget
self.layout.addWidget(self.tabs)
self.setLayout(self.layout)
def on_click_login(self):
global validUser
global app
textboxValue = self.loginTextbox.text()
if(textboxValue.lower() == 'pass'):
validUser=True
#the solutions i have been trying
self.menu.layout.removeWidget(self.menuInvalidUserLogin)
self.layout.removeWidget(self.menuInvalidUserLogin)
self.menu.layout.update()
QMessageBox.question(self, 'Response', "Login successful: Welcome", QMessageBox.Ok,QMessageBox.Ok)
else:
validUser=False
QMessageBox.question(self, 'Response', "Login unsuccessful: EXPLAIN YOURSELF", QMessageBox.Ok,QMessageBox.Ok)
self.loginTextbox.setText("")
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
expected results should be that the old widget is removed, new widget is added and then the layout those widgets are a part of is refreshed
Is this what you were expecting?
Also, is there a specific reason why you are using global variables in your class? It is bad practice, you should make them class members.
from PyQt5 import QtWidgets, QtCore, QtGui
import sys
class App(QtWidgets.QMainWindow):
def __init__(self):
super(App,self).__init__()
app = QtWidgets.QApplication.instance()
screen = app.primaryScreen().size()
self.title = 'Restaurant Application'
width = screen.width()
height = screen.height()
self.left = 0
self.top = 0
self.width = width
self.height = height
self.setMouseTracking(True)
self.table_widget = MyTableWidget(self)
self.setCentralWidget(self.table_widget)
self.initUI()
self.show()
def initUI(self):
# window
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
# statusbar
self.statusBar().showMessage('Welcome to el restaurante')
def mousePressEvent(self, event):
print('Mouse coords: ( %d : %d )' % (event.x(), event.y()))
class MyTableWidget(QtWidgets.QWidget):
def __init__(self, parent):
super(MyTableWidget, self).__init__(parent)
self.layout = QtWidgets.QVBoxLayout()
self.validUser = False
# Initialize tab screen
self.tabs = QtWidgets.QTabWidget()
self.login = QtWidgets.QWidget()
self.menu = QtWidgets.QWidget()
self.checkOut = QtWidgets.QWidget()
self.tabs.resize(500, 200)
# Add tabs
self.tabs.addTab(self.login, "Login")
self.tabs.addTab(self.menu, "Menu")
self.tabs.addTab(self.checkOut, "Check out")
# Create login tab
self.login.layout = QtWidgets.QVBoxLayout()
self.menu.layout = QtWidgets.QVBoxLayout()
# login text
self.loginPrompt = QtWidgets.QLabel("Please provide a valid login")
self.loginPrompt.setFixedSize(315,30)
self.loginPromptFont = QtGui.QFont("Times", 27, QtGui.QFont.Bold)
self.loginPrompt.setFont(self.loginPromptFont)
self.login.layout.addWidget(self.loginPrompt)
self.login.setLayout(self.login.layout)
# Create textbox
self.loginTextbox = QtWidgets.QLineEdit()
self.loginTextbox.returnPressed.connect(self.on_click_login)
self.loginTextbox.setFixedSize(170,20)
# Create a button in the window
self.loginButton = QtWidgets.QPushButton('Login button')
self.loginButton.clicked.connect(self.on_click_login)
self.loginButton.setFixedSize(100,40)
self.login.layout.addWidget(self.loginTextbox,alignment=QtCore.Qt.AlignCenter)
self.login.layout.addWidget(self.loginButton,alignment=QtCore.Qt.AlignCenter)
#widget code i use to decide which widget to add
self.menuInvalidUserLogin = QtWidgets.QLabel("Please login in to view")
self.menuValidUserLogin = QtWidgets.QLabel("Here's the menu")
if(self.validUser):
self.menu.layout.addWidget(self.menuValidUserLogin)
else:
self.menu.layout.addWidget(self.menuInvalidUserLogin)
self.menu.setLayout(self.menu.layout)
# Add tabs to widget
self.layout.addWidget(self.tabs)
self.setLayout(self.layout)
def on_click_login(self):
textboxValue = self.loginTextbox.text()
if(textboxValue.lower() == 'pass'):
self.validUser=True
for i in reversed(range(self.menu.layout.count())):
widgetToRemove = self.menu.layout.itemAt(i).widget()
self.menu.layout.removeWidget(widgetToRemove)
widgetToRemove.deleteLater()
self.menu.layout.addWidget(self.menuValidUserLogin)
QtWidgets.QMessageBox.question(self, 'Response', "Login successful: Welcome", QtWidgets.QMessageBox.Ok,QtWidgets.QMessageBox.Ok)
self.tabs.setCurrentIndex(1)
else:
self.validUser=False
QtWidgets.QMessageBox.question(self, 'Response', "Login unsuccessful: EXPLAIN YOURSELF", QtWidgets.QMessageBox.Ok,QtWidgets.QMessageBox.Ok)
self.loginTextbox.setText("")
def main():
app = QtWidgets.QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
if __name__ == "__main__":
main()

PySide/PyQt Overlay widget

I am trying to achieve something like this in PySide: https://codepen.io/imprakash/pen/GgNMXO
What I want to do is create a child window frameless with a black overlay below.
I didn't succeed to create a child window frameless and the overlay...
This is a base code to replicate the HTML:
from PySide import QtCore, QtGui
import sys
class MainWindow(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.resize(800, 500)
self.button = QtGui.QPushButton("Click Me")
self.setLayout(QtGui.QVBoxLayout())
self.layout().addWidget(self.button)
# Connections
self.button.clicked.connect(self.displayOverlay)
def displayOverlay(self):
popup = QtGui.QDialog(self)
popup.setWindowFlags(QtCore.Qt.FramelessWindowHint)
popup.setLayout(QtGui.QHBoxLayout())
popup.layout().addWidget(QtGui.QLabel("HI"))
popup.show()
print "clicked"
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
If you comment the line with the FramelessWindowHint, the window comes, else nothing happen...
I really hope that someone could help me. Thank you for the time you spent to read my question.
I'll be using PyQt5 for this explanation. It might have some differences to PySide (which I'm not sure if its still maintained) and PyQt4, but it shouldn't be too hard to convert.
The following example has a parent widget which a few buttons. One of them (the obvious one) calls for the popup. I've prepared the example to deal with the parent resize but have not made any code regarding mouse events of dragging the popup (see mouseMoveEvent and mouseReleaseEvent for that).
So here is the code:
import sys
from PyQt5 import QtWidgets, QtCore, QtGui
class TranslucentWidgetSignals(QtCore.QObject):
# SIGNALS
CLOSE = QtCore.pyqtSignal()
class TranslucentWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(TranslucentWidget, self).__init__(parent)
# make the window frameless
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
self.fillColor = QtGui.QColor(30, 30, 30, 120)
self.penColor = QtGui.QColor("#333333")
self.popup_fillColor = QtGui.QColor(240, 240, 240, 255)
self.popup_penColor = QtGui.QColor(200, 200, 200, 255)
self.close_btn = QtWidgets.QPushButton(self)
self.close_btn.setText("x")
font = QtGui.QFont()
font.setPixelSize(18)
font.setBold(True)
self.close_btn.setFont(font)
self.close_btn.setStyleSheet("background-color: rgb(0, 0, 0, 0)")
self.close_btn.setFixedSize(30, 30)
self.close_btn.clicked.connect(self._onclose)
self.SIGNALS = TranslucentWidgetSignals()
def resizeEvent(self, event):
s = self.size()
popup_width = 300
popup_height = 120
ow = int(s.width() / 2 - popup_width / 2)
oh = int(s.height() / 2 - popup_height / 2)
self.close_btn.move(ow + 265, oh + 5)
def paintEvent(self, event):
# This method is, in practice, drawing the contents of
# your window.
# get current window size
s = self.size()
qp = QtGui.QPainter()
qp.begin(self)
qp.setRenderHint(QtGui.QPainter.Antialiasing, True)
qp.setPen(self.penColor)
qp.setBrush(self.fillColor)
qp.drawRect(0, 0, s.width(), s.height())
# drawpopup
qp.setPen(self.popup_penColor)
qp.setBrush(self.popup_fillColor)
popup_width = 300
popup_height = 120
ow = int(s.width()/2-popup_width/2)
oh = int(s.height()/2-popup_height/2)
qp.drawRoundedRect(ow, oh, popup_width, popup_height, 5, 5)
font = QtGui.QFont()
font.setPixelSize(18)
font.setBold(True)
qp.setFont(font)
qp.setPen(QtGui.QColor(70, 70, 70))
tolw, tolh = 80, -5
qp.drawText(ow + int(popup_width/2) - tolw, oh + int(popup_height/2) - tolh, "Yep, I'm a pop up.")
qp.end()
def _onclose(self):
print("Close")
self.SIGNALS.CLOSE.emit()
class ParentWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ParentWidget, self).__init__(parent)
self._popup = QtWidgets.QPushButton("Gimme Popup!!!")
self._popup.setFixedSize(150, 40)
self._popup.clicked.connect(self._onpopup)
self._other1 = QtWidgets.QPushButton("A button")
self._other2 = QtWidgets.QPushButton("A button")
self._other3 = QtWidgets.QPushButton("A button")
self._other4 = QtWidgets.QPushButton("A button")
hbox = QtWidgets.QHBoxLayout()
hbox.addWidget(self._popup)
hbox.addWidget(self._other1)
hbox.addWidget(self._other2)
hbox.addWidget(self._other3)
hbox.addWidget(self._other4)
self.setLayout(hbox)
self._popframe = None
self._popflag = False
def resizeEvent(self, event):
if self._popflag:
self._popframe.move(0, 0)
self._popframe.resize(self.width(), self.height())
def _onpopup(self):
self._popframe = TranslucentWidget(self)
self._popframe.move(0, 0)
self._popframe.resize(self.width(), self.height())
self._popframe.SIGNALS.CLOSE.connect(self._closepopup)
self._popflag = True
self._popframe.show()
def _closepopup(self):
self._popframe.close()
self._popflag = False
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
main = ParentWidget()
main.resize(500, 500)
main.show()
sys.exit(app.exec_())
Which results in the following:
The logic is the following. You create an empty Widget and manually draw the background and popup (paintEvent). You add a button for closing the popup. For this you build a Signal and let the parent widget do the closing. This is important because you need to make the parent widget control some important elements of the popup (such as closing, resizng, etc.). You can add far more complexity but hopefully the example will suffice for starters.
Thanks to armatita, I succeed to get what I wanted. For now, there are some issues but it works and I get the result that I wanted.
I give you the code to the next who will be looking for the same thing.
from PySide import QtCore, QtGui
import sys
class CtmWidget(QtGui.QWidget):
def __init__(self, parent = None):
QtGui.QWidget.__init__(self, parent)
self.button = QtGui.QPushButton("Close Overlay")
self.setLayout(QtGui.QHBoxLayout())
self.layout().addWidget(self.button)
self.button.clicked.connect(self.hideOverlay)
def paintEvent(self, event):
painter = QtGui.QPainter()
painter.begin(self)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
path = QtGui.QPainterPath()
path.addRoundedRect(QtCore.QRectF(self.rect()), 10, 10)
mask = QtGui.QRegion(path.toFillPolygon().toPolygon())
pen = QtGui.QPen(QtCore.Qt.white, 1)
painter.setPen(pen)
painter.fillPath(path, QtCore.Qt.white)
painter.drawPath(path)
painter.end()
def hideOverlay(self):
self.parent().hide()
class Overlay(QtGui.QWidget):
def __init__(self, parent, widget):
QtGui.QWidget.__init__(self, parent)
palette = QtGui.QPalette(self.palette())
palette.setColor(palette.Background, QtCore.Qt.transparent)
self.setPalette(palette)
self.widget = widget
self.widget.setParent(self)
def paintEvent(self, event):
painter = QtGui.QPainter()
painter.begin(self)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
painter.fillRect(event.rect(), QtGui.QBrush(QtGui.QColor(0, 0, 0, 127)))
painter.end()
def resizeEvent(self, event):
position_x = (self.frameGeometry().width()-self.widget.frameGeometry().width())/2
position_y = (self.frameGeometry().height()-self.widget.frameGeometry().height())/2
self.widget.move(position_x, position_y)
event.accept()
class MainWindow(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.resize(800, 500)
self.button = QtGui.QPushButton("Click Me")
self.setLayout(QtGui.QVBoxLayout())
self.layout().addWidget(self.button)
self.popup = Overlay(self, CtmWidget())
self.popup.hide()
# Connections
self.button.clicked.connect(self.displayOverlay)
def displayOverlay(self):
self.popup.show()
print "clicked"
def resizeEvent(self, event):
self.popup.resize(event.size())
event.accept()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
Once again thank you both of you(ymmx and armatita) to spend time on my issue.
did you try replacing popup.show() by popup.exec_()? and remove self as a parameter of the Qdialog? I change QDialog to QmessageBox to be able to quit the subwindow but it still work with the QDialog.
popup = QMessageBox()
popup.setWindowFlags( Qt.FramelessWindowHint)
popup.setLayout( QHBoxLayout())
popup.layout().addWidget( QLabel("HI"))
popup.exec_()
update
class Popup(QDialog ):
def __init__(self):
super().__init__()
self.setWindowFlags( Qt.CustomizeWindowHint)
self.setLayout( QHBoxLayout())
Button_close = QPushButton('close')
self.layout().addWidget( QLabel("HI"))
self.layout().addWidget( Button_close)
Button_close.clicked.connect( self.close )
self.exec_()
print("clicked")
def mousePressEvent(self, event):
self.oldPos = event.globalPos()
def mouseMoveEvent(self, event):
delta = QPoint (event.globalPos() - self.oldPos)
#print(delta)
self.move(self.x() + delta.x(), self.y() + delta.y())
self.oldPos = event.globalPos()
class MainWindow( QWidget):
def __init__(self):
QWidget.__init__(self)
self.resize(800, 500)
self.button = QPushButton("Click Me")
self.setLayout( QVBoxLayout())
self.layout().addWidget(self.button)
# Connections
self.button.clicked.connect(self.displayOverlay)
def displayOverlay(self):
Popup( )
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())

Using button and objects in pyqt

class Window(QtGui.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.tabs()
def home(self):
df = QtGui.QPushButton('hello', self)
df.move(300, 300)
self.show()
def tabs(self):
btn_1 = QtGui.QPushButton('Home', self)
btn_1.clicked.connect(self.home)
self.show()
Trying to access the module 'home()' and print button 'hello' when button btn_1 in module tabs is clicked. Not happening..
When you create the new object it appears hidden, so that it is visible uses the show() function.
def home(self):
df = QtGui.QPushButton('hello', self)
df.move(300, 300)
df.show()

pyqt5 show which button was clicked

I am new to PyQT5 and I want to have several buttons and have the one clicked last in a "checked" state. When another button is clicked the previous one gets "unchecked" while the clicked one gets "checked".
import sys
from PyQt5.QtWidgets import *
class Example(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(30, 30, 400, 200)
self.initUI()
def initUI(self):
self.button1 = QPushButton(self)
self.button1.setGeometry(40, 40, 100, 50)
self.button1.setText("Button 1")
self.button2 = QPushButton(self)
self.button2.setGeometry(150, 40, 100, 50)
self.button2.setText("Button 2")
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
Building off of your code, you can add button1 and button2 to a QButtonGroup with the exclusive property set to True.
class Example(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(30, 30, 400, 200)
self.initUI()
def initUI(self):
self.button1 = QPushButton(self)
self.button1.setGeometry(40, 40, 100, 50)
self.button1.setText("Button 1")
self.button2 = QPushButton(self)
self.button2.setGeometry(150, 40, 100, 50)
self.button2.setText("Button 2")
self.btn_grp = QButtonGroup()
self.btn_grp.setExclusive(True)
self.btn_grp.addButton(self.button1)
self.btn_grp.addButton(self.button2)
self.btn_grp.buttonClicked.connect(self.on_click)
self.show()
def on_click(self, btn):
pass # do something with the button clicked
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
Here I've also connected an empty slot to the signal QButtonGroup.buttonClicked, which is emitted whenever a button from the group is clicked.
To find out which button is the currently checked button, you can invoke the methods QButtonGroup.checkedButton() and QButtonGroup.checkedId(). The former will return a QButton object and the latter will return an index int, corresponding to the order in which the buttons were added to the group.
You can use functools partial or the sender method to check which button was pressed:
import sys
from PyQt5.QtWidgets import *
from functools import partial
class Example(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(30, 30, 400, 200)
self.initUI()
def initUI(self):
self.button1 = QPushButton(self)
self.button1.setGeometry(40, 40, 100, 50)
self.button1.setText("Button 1")
self.button1.clicked.connect(partial(self.clicked_btn, 'Button 1'))
self.button2 = QPushButton(self)
self.button2.setGeometry(150, 40, 100, 50)
self.button2.setText("Button 2")
self.button2.clicked.connect(partial(self.clicked_btn, 'Button 2'))
self.show()
def clicked_btn(self, value):
print(f'{value} clicked')
sender = self.sender()
print(f'Sender says: {sender.text()} was clicked')
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
Make the buttons checkable by setCheckable(True)
Add the buttons to a QButtonGroup() and the rest is sorted automatically:
class Example(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(30, 30, 400, 200)
self.initUI()
def initUI(self):
self.button1 = QPushButton(self)
self.button1.setGeometry(40, 40, 100, 50)
self.button1.setText("Button 1")
self.button1.setCheckable(True)
self.button2 = QPushButton(self)
self.button2.setGeometry(150, 40, 100, 50)
self.button2.setText("Button 2")
self.button2.setCheckable(True)
self.my_button_group = QButtonGroup()
self.my_button_group.addButton(self.button1)
self.my_button_group.addButton(self.button2)
self.show()

QCoreApplication::exec: The event loop is already running

I just started with programming, started using Python and PyQt4. And got this error:
QCoreApplication::exec: The event loop is already running
Basically i wanted to write a function which, when you press a button, opens a new gui window(while the previous one wouldnt exist at that point) with completely new layout.
Is there a way how to fix the script or write it in another way to get the outcome?
import sys
from PyQt4 import QtGui, QtCore
class Window(QtGui.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.setGeometry(50, 50 , 1280, 720)
self.setWindowTitle("Main")
self.setWindowIcon(QtGui.QIcon("smili.png"))
extractAction = QtGui.QAction("Exit", self)
extractAction.setShortcut("Ctrl+Q")
extractAction.setStatusTip("Press to leave the app.")
extractAction.triggered.connect(self.close_appllication)
self.statusBar()
mainMenu = self.menuBar()
fileMenu = mainMenu.addMenu("Menu")
fileMenu.addAction(extractAction)
self.home()
def home(self):
btn = QtGui.QPushButton("Quit", self)
btn.clicked.connect(QtCore.QCoreApplication.instance() .quit)
btn.resize(250,50)
btn.move(100,600)
btn.setStyleSheet('QPushButton{background-color:#8A0808;color:#000000;font-size:25px;border:5px}')
btn = QtGui.QPushButton("Start", self)
btn.clicked.connect(self.redirect_window)
btn.resize(250,50)
btn.move(100,200)
btn.setStyleSheet('QPushButton{background-color:#8A0808;color:#000000;font-size:25px;border:5px}')
extractAction = QtGui.QAction(QtGui.QIcon("exitb.png"), "Exit the application.", self)
extractAction.triggered.connect(self.close_appllication)
self.toolBar = self.addToolBar("ToolBar")
self.toolBar.addAction(extractAction)
checkBox = QtGui.QCheckBox("Enlarge Window", self)
checkBox.move(100, 25)
checkBox.stateChanged.connect(self.enlarge_window)
self.show()
def redirect_window(self):
class startWindow(QtGui.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.setGeometry(50, 50 , 1280, 720)
self.setWindowTitle("Main/Start")
self.setWindowIcon(QtGui.QIcon("smili.png"))
extractAction = QtGui.QAction("Exit", self)
extractAction.setShortcut("Ctrl+Q")
extractAction.setStatusTip("Press to leave the app.")
extractAction.triggered.connect(self.close_appllication)
self.statusBar()
mainMenu = self.menuBar()
fileMenu = mainMenu.addMenu("Menu")
fileMenu.addAction(extractAction)
self.home()
main()
def enlarge_window(self, state):
if state == QtCore.Qt.Checked:
self.setGeometry(50,50,1920,1080)
else:
self.setGeometry(50,50,1280,720)
def close_appllication(self):
print("Shutting down!")
sys.exit()
def main():
app = QtGui.QApplication(sys.argv)
GUI = Window()
sys.exit(app.exec_())
main()

Categories

Resources