Close and Open new Window PYQT5 - python

I would like to press a button in a window and close that window,after that open a new window
How can I do it?
I already tried it but it sends this message the console:
QCoreApplication::exec: The event loop is already running
class Window(QWidget):
def __init__(self,parent = None):
super().__init__(parent)
self.title = 'pySim Z-eighty'
self.left = 0
self.top = 0
self.width = 1200
self.height = 3000
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.button = QPushButton("Z80")
self.button1 = QPushButton()
self.button2 = QPushButton()
self.container = QWidget()
self.layout = QGridLayout()
self.layout.addWidget(self.button1, 1, 0)
self.layout.addWidget(self.button, 1, 1)
self.layout.addWidget(self.button2, 1, 2)
self.container.setLayout(self.layout)
self.layoutPrincipal = QBoxLayout(0)
self.layoutPrincipal.addWidget(self.container)
self.setLayout(self.layoutPrincipal)
self.button.pressed.connect(self.IniciarInterfaz)
def IniciarInterfaz(self):
self.hide()
app = QApplication(sys.argv)
ex = mainWindow()
ex.setStyleSheet("background-color: #fff")
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Window()
ex.show()
sys.exit(app.exec_())
My main problem is when i pressed the button I can't open the new window

There can only be one QApplication within the PyQt application, so if you already created it, do not do it again.
Another problem is that the variables exist only within the context, in your case mainWindow, so at the end of the function StartInterface will eliminate this variable and the window, the solution is to make the mainWindow member of the class, so the context will be the class and no longer the function, so it will stay correctly.
def IniciarInterfaz(self):
self.hide()
self.ex = mainWindow()
self.ex.setStyleSheet("background-color: #fff")
self.ex.show()

PYQT No open and close method,...
hide() and show() method you can use buttons what ever you want,...
def PlatformType_Clicked(self):
dialog.hide()
dialog1.show()

Related

change label from other class in a different file

I am creating an application where I have a main window whit a label and then a docked widget that is in another file. I want to change the main windows label from a button at the docked widget. I try to import the main window file but then I can not access to the label. And I also tried to call a function in the main windows that changes the label but then the label does not change.
Here is the code:
main_window.py:
import results_window
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.define_main_windows()
self.create_dock_widgets()
def define_main_windows(self):
# Define de Main window properties
self.setMinimumSize(QSize(300, 100))
self.setWindowTitle("Python SkyLibris")
self.setWindowIcon(QtGui.QIcon("skylibris_icon.png"))
self.setStyleSheet("QMainWindow {background: 'white';}")
self.top = 50
self.left = 0
self.width = 1300
self.height = 400
self.setGeometry(self.left, self.top, self.width, self.height)
self.result = QLabel("result:")
self.setCentralWidget(self.result)
def create_dock_widgets(self):
# Create dock widgets
self.results_window = results_window.results_window()
self.resultsWindowDock = QDockWidget("Results Viewer", self)
self.resultsWindowDock.setWidget(self.results_window )
self.resultsWindowDock.setFloating(False)
self.resultsWindowDock.setVisible(True)
self.addDockWidget(Qt.LeftDockWidgetArea, self.resultsWindowDock)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
app.setStyle('Fusion')
mainWin = MainWindow()
mainWin.show()
sys.exit(app.exec_())
results_window.py:
import main_window
class results_window(QWidget):
def __init__(self):
super(results_window, self).__init__()
print("init")
self.label = QLabel()
self.value = QLineEdit()
self.bt = QPushButton("Click")
self.bt.clicked.connect(self.clickMethod)
self.main_layout = QVBoxLayout()
self.main_layout.addWidget(self.label)
self.main_layout.addWidget(self.value)
self.main_layout.addWidget(self.bt)
self.setLayout(self.main_layout)
def clickMethod(self):
print(self.value.text())
text = self.value.text()
main_window.result.setText(text)
You are using the wrong tools, for example your code has a circular import that causes your application to close since it is equivalent to a while True.
In Qt, signals and slots are used to share data asynchronously, as well as contributing to the fact that there is no coupling between classes. In your case, Results_Window must have a signal that transmits that information to the MainWindow, this signal must be emit within clickMethod.
results_window.py
from PyQt5 import QtCore, QtWidgets
class Results_Window(QtWidgets.QWidget):
resultChanged = QtCore.pyqtSignal(str)
def __init__(self):
super(Results_Window, self).__init__()
print("init")
self.label = QtWidgets.QLabel()
self.value = QtWidgets.QLineEdit()
self.bt = QtWidgets.QPushButton("Click")
self.bt.clicked.connect(self.clickMethod)
main_layout = QtWidgets.QVBoxLayout(self)
main_layout.addWidget(self.label)
main_layout.addWidget(self.value)
main_layout.addWidget(self.bt)
#QtCore.pyqtSlot()
def clickMethod(self):
text = self.value.text()
self.resultChanged.emit(text)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
app.setStyle('Fusion')
w = Results_Window()
w.show()
sys.exit(app.exec_())
main_window.py
from PyQt5 import QtCore, QtGui, QtWidgets
import results_window
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.define_main_windows()
self.create_dock_widgets()
def define_main_windows(self):
self.setMinimumSize(QtCore.QSize(300, 100))
self.setWindowTitle("Python SkyLibris")
self.setWindowIcon(QtGui.QIcon("skylibris_icon.png"))
self.setStyleSheet("QMainWindow {background: 'white';}")
top, left, width, height = 50, 0, 1300, 400
self.setGeometry(left, top, width, height)
self.result = QtWidgets.QLabel("result:")
self.setCentralWidget(self.result)
def create_dock_widgets(self):
self.results_window = results_window.Results_Window()
self.results_window.resultChanged.connect(self.result.setText)
self.resultsWindowDock = QtWidgets.QDockWidget("Results Viewer", self)
self.resultsWindowDock.setWidget(self.results_window )
self.resultsWindowDock.setFloating(False)
self.resultsWindowDock.setVisible(True)
self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.resultsWindowDock)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
app.setStyle('Fusion')
mainWin = MainWindow()
mainWin.show()
sys.exit(app.exec_())
I had similar problem in PyQT5 where I was unable to access and set the local variables. After a lot of struggle I found writing to file and reading from file as the best solution. Simply write the desired output to file and access the same info from other file. Works great!

How do I add table to central widget in PyQt5 keeping my menu bar?

I am having trouble creating a PyQt5 GUI where I want a table of information as the central widget and a menu bar (which I will eventually put sorting options into). My code allows me to have either the table OR the menu but not both, and can't set a central widget because the class is not defined. Hopefully it's just something small I'm missing. Would appreciate any help, thanks.
Here is my code:
class Main(QMainWindow):
def __init__(self,parent = None):
super().__init__()
#self.grid_widget = App(grid)
self.initUI()
def initUI(self):
exitAct = QAction(QIcon('exit.png'), '&Exit', self)
exitAct.setShortcut('Ctrl+Q')
exitAct.setStatusTip('Exit application')
exitAct.triggered.connect(qApp.quit)
self.statusBar()
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(exitAct)
#self.setCentralWidget(self.grid_widget)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Main()
sys.exit(app.exec_())
class App(QWidget):
def __init__(self, parent = None):
super(App, self).__init__(parent)
self.title = 'PyQt5 table'
self.left = 90
self.top = 90
self.width = 800
self.height = 600
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.createTable()
# Add layout, add table to grid layout
grid = QGridLayout()
grid.addWidget(self.tableWidget)
self.setLayout(grid)
# Show widget
self.show()
def createTable(self):
# Create table
self.tableWidget = QTableWidget()
self.tableWidget.setRowCount(len(q1.index))
self.tableWidget.setColumnCount(len(q1.columns))
self.tableWidget.setHorizontalHeaderLabels(heads) #set column names to headers in df
for i in range(len(q1.index)):
for j in range(len(q1.columns)):
self.tableWidget.setItem(i, j, QTableWidgetItem(str(q1.iat[i, j])))
self.tableWidget.resizeColumnsToContents()
self.tableWidget.resizeRowsToContents()
self.tableWidget.move(0,0)
# table selection change
self.tableWidget.doubleClicked.connect(self.on_click)
#pyqtSlot()
def on_click(self):
print("\n")
for currentQTableWidgetItem in self.tableWidget.selectedItems():
print(currentQTableWidgetItem.row(), currentQTableWidgetItem.column(), currentQTableWidgetItem.text())
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
Which produces this:
and ignores my whole tablewidget altogether.
I have commented out the 3rd line in the QMainWindow because it produces an error saying that App is not defined.
How do I set the central widget so that it allows the table to appear as well? Thanks.
the application should only have a single main, to have several only the first one will be executed, and therefore everything that you are after will not be defined, and consequently App is not defined as you indicate.
So the solution is to eliminate the intermediate main and copy it to the final main.
class Main(QMainWindow):
def __init__(self,parent = None):
super().__init__()
self.grid_widget = App(self)
self.initUI()
...
class App(QWidget):
...
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Main()
sys.exit(app.exec_())

Clear Button PyQt5

I have been trying to build a simple GUI with:
A QLineEdit where the user writes a string
A QPushButton that clears whatever the user writes in the above lineedit every time I click on it.
My issue is in the second one. I have been trying to solve it by looking at solutions online but they weren't really useful so far. Can anyone give a hint on how to proceed?
Here is my code:
import sys
from PyQt5.QtWidgets import QWidget, QLineEdit
from PyQt5.QtWidgets import QLabel, QPushButton, QApplication
from PyQt5.QtCore import pyqtSlot
app = QApplication(sys.argv)
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'MyApp'
self.left = 10
self.top = 10
self.width = 800
self.height = 800
self.initUI()
self.show()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
# Create textbox for index number 1
self.nameLabel = QLabel(self)
self.nameLabel.setText('Insert something:')
self.nameLabel.move(20, 80)
self.textbox_index1 = QLineEdit(self)
self.textbox_index1.move(20, 100)
self.textbox_index1.resize(280, 40)
# Create a button in the window
self.buttonC1 = QPushButton('Clear', self)
self.buttonC1.move(300, 119)
# connect buttons "CLEAR" to function
self.buttonC1.clicked.connect(self.on_clickC1)
#pyqtSlot()
# Functions for the CLEAR buttons
def on_clickC1(self):
self.x1 = clearSearch1(self.textbox_index1.text(''))
return self.x1
def clearSearch1(self.x):
return self.x.clear()
if __name__ == '__main__':
app.aboutToQuit.connect(app.deleteLater)
ex = App()
sys.exit(app.exec_())
Thanks so much in advance,
Mattia
I do not understand what you are trying to do, the solution is simple, you must connect the clicked signal to the clear method directly without creating any other function:
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'MyApp'
self.left, self.top, self.width, self.height = 10, 10, 800, 800
self.initUI()
self.show()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
# Create textbox for index number 1
self.nameLabel = QLabel(self)
self.nameLabel.setText('Insert something:')
self.nameLabel.move(20, 80)
self.textbox_index1 = QLineEdit(self)
self.textbox_index1.move(20, 100)
self.textbox_index1.resize(280, 40)
# Create a button in the window
self.buttonC1 = QPushButton('Clear', self)
self.buttonC1.move(300, 119)
# connect buttons "CLEAR" to function
self.buttonC1.clicked.connect(self.textbox_index1.clear)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

Mdi sub window close

I would like to close the MDI subwindow with a push of a button within the window instead of closing it with the x at the top. I have another file with a few classes that has all of the information about the window that is opening up in the MDI area. I have tried self.close() but that leaves the window open and clears all of the widgets from the window. I will post the code below for how I am adding the subwindow to the MDI area.
subWindow = QtWidgets.QMdiSubWindow()
New_Window = NewMDIWindow()
subWindow.setWidget(New_Window)
subWindow.setObjectName("New_Window")
subWindow.setWindowTitle("New SubWindow")
self.MainUi.mdiArea.addSubWindow(subWindow )
subWindow.show()
The X button closes the QMdiSubWindow, not the widget inscribed on it, so the button should close the subwindow:
your_QPushButton.clicked.connect(your_QMdiSubWindow.close)
Complete Example:
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
QtWidgets.QMainWindow.__init__(self, parent)
self.centralwidget = QtWidgets.QWidget(self)
self.setCentralWidget(self.centralwidget)
self.centralwidget.setLayout(QtWidgets.QVBoxLayout(self.centralwidget))
self.mdiArea = QtWidgets.QMdiArea(self.centralwidget)
self.centralwidget.layout().addWidget(self.mdiArea)
subWindow = QtWidgets.QMdiSubWindow(self)
widget = QtWidgets.QWidget()
widget.setLayout(QtWidgets.QVBoxLayout())
btn = QtWidgets.QPushButton("close", widget)
widget.layout().addWidget(btn)
btn.clicked.connect(subWindow.close)
subWindow.setWidget(widget)
subWindow.setObjectName("New_Window")
subWindow.setWindowTitle("New SubWindow")
self.mdiArea.addSubWindow(subWindow)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())

widgets are not expandig according to window size

what is mistake in this code that prevents widgets from expanding according to window size ?
class FeedbackWindow(QWidget):
def __init__(self):
QWidget.__init__(self)
self.main_layout = QVBoxLayout(self)
self.main_widget = QWidget(self)
self.main_widget.setLayout(self.main_layout)
self.title_label = QLabel("Tell us what you think:")
self.feedback_text_editor = QTextEdit()
self.send_button = QPushButton("Send")
self.main_layout.addWidget(self.title_label)
self.main_layout.addWidget(self.feedback_text_editor)
self.main_layout.addWidget(self.send_button)
self.setWindowTitle("Feedback")
self.setGeometry(200,120,300,300)
if __name__ == "__main__":
app = QApplication(sys.argv)
w = FeedbackWindow()
w.show()
app.exec_()
the main layout and widget are connected to self, so it should take its dimension.
The code does not use self.main_widget. Remove self.main_widget:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class FeedbackWindow(QWidget):
def __init__(self):
QWidget.__init__(self)
self.main_layout = QVBoxLayout(self)
#self.main_widget = QWidget(self) # main_widget is not used.
#self.main_widget.setLayout(self.main_layout)
self.setLayout(self.main_layout)
self.title_label = QLabel("Tell us what you think:")
self.feedback_text_editor = QTextEdit()
self.send_button = QPushButton("Send")
self.main_layout.addWidget(self.title_label)
self.main_layout.addWidget(self.feedback_text_editor)
self.main_layout.addWidget(self.send_button)
self.setWindowTitle("Feedback")
self.setGeometry(200,120,300,300)
if __name__ == "__main__":
app = QApplication(sys.argv)
w = FeedbackWindow()
w.show()
app.exec_()
Remove
self.main_widget = QWidget(self)
self.main_widget.setLayout(self.main_layout)
You don't need them. In your implementation, the layout is set on self.main_widget which is NOT the main widget. Your main widget is your FeedbackWindows itself. When you call self.main_layout = QVBoxLayout(self), it implicitely apply the layout on the main widget.

Categories