PyQt application not functioning properly when being used with threads [duplicate] - pyqt5

This question already has answers here:
In PyQt, what is the best way to share data between the main window and a thread
(1 answer)
Example of the right way to use QThread in PyQt?
(3 answers)
Background thread with QThread in PyQt
(7 answers)
Closed 4 months ago.
I have created a UI which contains a text edit control. Below is its code:
home.py
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.textEdit = QtWidgets.QTextEdit(self.centralwidget)
self.textEdit.setGeometry(QtCore.QRect(130, 140, 301, 241))
self.textEdit.setObjectName("textEdit")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
Below is the main.py:
import sys
import time
from home import Ui_MainWindow
from PyQt5.QtWidgets import QApplication, QMainWindow
from threading import Thread
class UI(QMainWindow, Ui_MainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.textEdit.append("Application starting")
Thread(target=self.startProc).start()
def startProc(self):
i = 0
while True:
i = i + 1
self.ui.textEdit.append("Current value: {}".format(i))
time.sleep(1)
if i == 5:
break
app = QApplication(sys.argv)
main_window = UI()
main_window.show()
sys.exit(app.exec_())
So in above code, I am creating a thread (startProc) which runs for 5sec and then break. This code is working fine in Windows 10 and executes normally but when running it in Ubuntu 18.04, it runs fine and as soon as the thread stops, the whole app crashes with below errors:
QObject::connect: Cannot queue arguments of type 'QTextCursor'
(Make sure 'QTextCursor' is registered using qRegisterMetaType().)
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
Is there any specific reason that its working fine on Windows but not in Ubuntu? How can I resolve this issue?

Related

Qpushbutton in custom QlistWidgetItem doesn't respond when running on embedded device

I'm quite new to pyqt5 and applications on embedded devices, and was hoping someone may have any tips or suggestions on the problems I'm facing.
I am working with a pyqt5 appliaction where the widget contains a QListWidget and two buttons. I have made a seperate widget that I use as a customized QListWidgetItem. The customized QListWidgetItem contains a textfield and a QPushButton.
Everything works perfectly on Ubuntu on my computer, but when I deploy and run the app on an embedded device, the buttons in the customized QListWidgetItem no longer responds. The "normal" buttons, that are not in the customized QListWidgetItem, still works normally.
I can't find a reason or fixes for this, and am quite stuck..
Here's my code, very simplified:
Edit! After some feedback I've created a smaller representation of the app/problem, which hopefully can make it easier to debug.
I no longer use pyqtSignal between the classes, only connected the buttons to different functions directly.
In this case, both the printing and color changing will happen if the buttons respond correctly.
python file:
import sys
from CustomListItem import Ui_custom_list_widget
from CollectorWidget import Ui_collector_widget
from PyQt5.QtWidgets import QWidget, QListWidgetItem, QApplication, QStackedWidget, QMainWindow
def main():
app = QApplication(sys.argv)
stack = QStackedWidget()
collector = CollectorWidget()
stack.addWidget(collector)
stack.setCurrentWidget(collector)
stack.show()
sys.exit(app.exec_())
class CollectorWidget(Ui_collector_widget, QWidget):
temp_list_items = []
def __init__(self, parent=None):
super(CollectorWidget, self).__init__(parent)
self.setupUi(self)
self.create_item_button.clicked.connect(self.create_item_clicked)
self.another_button.clicked.connect(lambda: print("this one works"))
def create_item_clicked(self):
self.listItem = QListWidgetItem()
self.item = CustomListItem()
self.item.custom_item_button.clicked.connect(self.test_signal)
self.qlistwidget_list.addItem(self.listItem)
self.qlistwidget_list.setItemWidget(self.listItem, self.item)
self.temp_list_items.append((self.listItem, self.item))
def test_signal(self):
print("--------------IT'S WORKING!--------------------------")
class CustomListItem(Ui_custom_list_widget, QWidget):
def __init__(self):
super().__init__()
self.setupUi(self)
self.item_name.setText("testing testing")
self.custom_item_button.clicked.connect(self.button_clicked)
def setItemText(self, text):
self.item_name.setText(text)
def button_clicked(self):
self.item_name.setStyleSheet("background-color: red;")
if __name__ == "__main__":
main()
Ui files (collector):
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'CollectorWidget.ui'
#
# Created by: PyQt5 UI code generator 5.15.6
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_collector_widget(object):
def setupUi(self, collector_widget):
collector_widget.setObjectName("collector_widget")
collector_widget.resize(625, 514)
self.verticalLayout = QtWidgets.QVBoxLayout(collector_widget)
self.verticalLayout.setObjectName("verticalLayout")
self.qlistwidget_list = QtWidgets.QListWidget(collector_widget)
self.qlistwidget_list.setObjectName("qlistwidget_list")
self.verticalLayout.addWidget(self.qlistwidget_list)
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.create_item_button = QtWidgets.QPushButton(collector_widget)
self.create_item_button.setObjectName("create_item_button")
self.horizontalLayout.addWidget(self.create_item_button)
self.another_button = QtWidgets.QPushButton(collector_widget)
self.another_button.setObjectName("another_button")
self.horizontalLayout.addWidget(self.another_button)
self.verticalLayout.addLayout(self.horizontalLayout)
self.retranslateUi(collector_widget)
QtCore.QMetaObject.connectSlotsByName(collector_widget)
def retranslateUi(self, collector_widget):
_translate = QtCore.QCoreApplication.translate
collector_widget.setWindowTitle(_translate("collector_widget", "Form"))
self.create_item_button.setText(_translate("collector_widget", "Create"))
self.another_button.setText(_translate("collector_widget", "Just a button"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
collector_widget = QtWidgets.QWidget()
ui = Ui_collector_widget()
ui.setupUi(collector_widget)
collector_widget.show()
sys.exit(app.exec_())
Ui files (custom_list_item):
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'CustomListItem.ui'
#
# Created by: PyQt5 UI code generator 5.15.6
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_custom_list_widget(object):
def setupUi(self, custom_list_widget):
custom_list_widget.setObjectName("custom_list_widget")
custom_list_widget.resize(608, 40)
self.horizontalLayout = QtWidgets.QHBoxLayout(custom_list_widget)
self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout.setSpacing(0)
self.horizontalLayout.setObjectName("horizontalLayout")
self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.item_name = QtWidgets.QLabel(custom_list_widget)
font = QtGui.QFont()
font.setKerning(True)
self.item_name.setFont(font)
self.item_name.setStyleSheet("")
self.item_name.setWordWrap(True)
self.item_name.setObjectName("item_name")
self.horizontalLayout_2.addWidget(self.item_name)
self.custom_item_button = QtWidgets.QPushButton(custom_list_widget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.custom_item_button.sizePolicy().hasHeightForWidth())
self.custom_item_button.setSizePolicy(sizePolicy)
self.custom_item_button.setMaximumSize(QtCore.QSize(20, 20))
self.custom_item_button.setStyleSheet("")
self.custom_item_button.setText("")
self.custom_item_button.setObjectName("custom_item_button")
self.horizontalLayout_2.addWidget(self.custom_item_button)
self.horizontalLayout.addLayout(self.horizontalLayout_2)
self.retranslateUi(custom_list_widget)
QtCore.QMetaObject.connectSlotsByName(custom_list_widget)
def retranslateUi(self, custom_list_widget):
_translate = QtCore.QCoreApplication.translate
custom_list_widget.setWindowTitle(_translate("custom_list_widget", "Form"))
self.item_name.setText(_translate("custom_list_widget", "TextLabel"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
custom_list_widget = QtWidgets.QWidget()
ui = Ui_custom_list_widget()
ui.setupUi(custom_list_widget)
custom_list_widget.show()
sys.exit(app.exec_())
Picture of app:

PYQT5 webcam is not opening on the label

I am trying to set my webcam to a label and open it on pageload. However code does not throw any error also it does not getting bind to the label as well. Can anyone tell me how to fix this?
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'camera.ui'
#
# Created by: PyQt5 UI code generator 5.15.2
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow,qApp
import sys
import cv2
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayoutWidget = QtWidgets.QWidget(self.centralwidget)
self.gridLayoutWidget.setGeometry(QtCore.QRect(169, 59, 471, 251))
self.gridLayoutWidget.setObjectName("gridLayoutWidget")
self.gridLayout = QtWidgets.QGridLayout(self.gridLayoutWidget)
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.gridLayout.setObjectName("gridLayout")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 26))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.label = QtWidgets.QLabel(self.gridLayoutWidget)
self.label.setObjectName("label")
self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
self.capture = cv2.cv2.VideoCapture(0)
timer = QtCore.QTimer()
timer.setInterval(int(1000/30))
timer.timeout.connect(self.get_frame)
timer.start()
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def get_frame(self):
frame = self.capture.read()
image = QtGui.QImage(frame, *frame.shape[1::-1], QtGui.QImage.Format_RGB888).rgbSwapped()
pixmap = QtGui.QPixmap.fromImage(image)
self.label.setPixmap(pixmap)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
The problem is that timer is a local variable that will be destroyed so the get_frame method will not be invoked, the solution is to make it a member of the class so you must change timer to self.timer. Also the read() method returns a tuple, no the frame so you should change it to:
def get_frame(self):
ret, frame = self.capture.read()
if ret:
image = QtGui.QImage(
frame, *frame.shape[1::-1], QtGui.QImage.Format_RGB888
).rgbSwapped()
pixmap = QtGui.QPixmap.fromImage(image)
self.label.setPixmap(pixmap)

I can't get Qt.FramelessWindowHint to work [duplicate]

This question already has answers here:
QtDesigner changes will be lost after redesign User Interface
(2 answers)
Closed 2 years ago.
I have been trying to figure this out for the last two days. I want to make my window frameless, I saw in a couple of resources that I should be using Qt.FramelessWindowHint . However, it doesn't want to work and I can't figure out why.
Can someone please point out what's wrong with my code, as I am very new to PyQt5?
(I have commented out sections that are related to some other files)
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtCore import QTimer, Qt
#from HomeWindow import Ui_Form
class Ui_MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
#def secondscreen(self):
#self.Form = QtWidgets.QWidget()
#self.ui = Ui_Form()
#self.ui.setupUi(self.Form)
#self.Form.showMaximized()
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(560, 350)
MainWindow.setStyleSheet("background-color: rgb(255, 255, 255);")
flags = Qt.WindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
self.setWindowFlags(flags)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.textBrowser = QtWidgets.QTextBrowser(self.centralwidget)
self.textBrowser.setGeometry(QtCore.QRect(80, 280, 470, 60))
self.textBrowser.setFrameShape(QtWidgets.QFrame.NoFrame)
self.textBrowser.setFrameShadow(QtWidgets.QFrame.Plain)
self.textBrowser.setObjectName("textBrowser")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(10, 270, 61, 71))
self.label.setText("")
self.label.setPixmap(QtGui.QPixmap("../Media/College Logo.png"))
self.label.setScaledContents(True)
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(290, 60, 220, 80))
font = QtGui.QFont()
font.setPointSize(28)
self.label_2.setFont(font)
self.label_2.setObjectName("label_2")
self.label_3 = QtWidgets.QLabel(self.centralwidget)
self.label_3.setGeometry(QtCore.QRect(290, 140, 81, 16))
font = QtGui.QFont()
font.setPointSize(9)
self.label_3.setFont(font)
self.label_3.setObjectName("label_3")
self.label_4 = QtWidgets.QLabel(self.centralwidget)
self.label_4.setGeometry(QtCore.QRect(0, 20, 231, 211))
self.label_4.setText("")
self.label_4.setPixmap(QtGui.QPixmap("../Media/Smample Logo.png"))
self.label_4.setScaledContents(True)
self.label_4.setAlignment(QtCore.Qt.AlignCenter)
self.label_4.setObjectName("label_4")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(290, 190, 93, 28))
self.pushButton.setObjectName("pushButton")
#self.pushButton.clicked.connect(self.secondscreen)
#self.pushButton.clicked.connect(MainWindow.close)
#QTimer.singleShot (5000, self.secondscreen)
#QTimer.singleShot (5001, MainWindow.close)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.textBrowser.setHtml(_translate("MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:7.8pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'MS Shell Dlg 2\';\">(c) 2020 SQU, Inc. Protected by international patents. See Squ.om/patents. App name is a registered trademark of SQU, Inc. Other product or brand names may be trademarks or registred trademarks of their respective holder.</span></p></body></html>"))
self.label_2.setText(_translate("MainWindow", "Mechanica"))
self.label_3.setText(_translate("MainWindow", "Version 1.0"))
self.pushButton.setText(_translate("MainWindow", "Start"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
You shouldn't try to edit or mimic the behavior of files generated by pyuic, as doing it leads to confusion about the object structure, and that's exactly your case.
Your Ui_MainWindow already inherits from QMainWindow, there's no use to create an instance of QMainWindow. In fact, what you're seeing is that QMainWindow, while you're setting the flag on the Ui_MainWindow instance, which you're never actually showing.
class Ui_MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
# ...
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
mainWindow = Ui_MainWindow()
mainWindow.show()
sys.exit(app.exec_())

Insert qtpynodeeditor in main window pyside2

I want to use node editor in pyside2, i got the library qtpynodeeditor (https://pypi.org/project/qtpynodeeditor/). I am not able to insert inside to my main window.
I am able to display separately, Left window is node editor right is main window.
MainWindow_UI.py
# -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'ListViewForNodeEditor_UI.ui'
##
## Created by: Qt User Interface Compiler version 5.14.1
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
################################################################################
from PySide2.QtCore import (QCoreApplication, QMetaObject, QObject, QPoint,
QRect, QSize, QUrl, Qt)
from PySide2.QtGui import (QBrush, QColor, QConicalGradient, QCursor, QFont,
QFontDatabase, QIcon, QLinearGradient, QPalette, QPainter, QPixmap,
QRadialGradient)
from PySide2.QtWidgets import *
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
if MainWindow.objectName():
MainWindow.setObjectName(u"MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QWidget(MainWindow)
self.centralwidget.setObjectName(u"centralwidget")
self.verticalLayout = QVBoxLayout(self.centralwidget)
self.verticalLayout.setObjectName(u"verticalLayout")
self.graphicsView = QGraphicsView(self.centralwidget)
self.graphicsView.setObjectName(u"graphicsView")
self.verticalLayout.addWidget(self.graphicsView)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QMenuBar(MainWindow)
self.menubar.setObjectName(u"menubar")
self.menubar.setGeometry(QRect(0, 0, 800, 21))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QStatusBar(MainWindow)
self.statusbar.setObjectName(u"statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QMetaObject.connectSlotsByName(MainWindow)
# setupUi
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QCoreApplication.translate("MainWindow", u"MainWindow", None))
# retranslateUi
NodeEditor.py
from ListViewForNodeEditor_UI import Ui_MainWindow
from PySide2.QtGui import *
from PySide2.QtWidgets import *
from PySide2.QtCore import *
import qdarkstyle
import qtpynodeeditor as nodeeditor
class testNode(QMainWindow):
def __init__(self, parent=None):
super(testNode, self).__init__(parent)
self.Wui = Ui_MainWindow()
self.Wui.setupUi(self)
#Shows the Node Editor
registry = nodeeditor.DataModelRegistry()
scene = nodeeditor.FlowScene(registry=registry)
self.view = nodeeditor.FlowView(scene)
self.view.show()
if __name__=="__main__":
import sys
app = QApplication(sys.argv)
dark_stylesheet = qdarkstyle.load_stylesheet_pyside2()
app.setStyleSheet(dark_stylesheet)
w = testNode()
w.show()
sys.exit(app.exec_())
any alternative node editor for pyside2 much appreciated.
You are showing the FlowView as a separate widget.
If you change the line
self.view.show()
to
self.Wui.verticalLayout.addWidget(self.view)
the FlowView will be added to your layout. See the Qt layout documentation for more information and examples.

How can I open and close a new window from main window in PyQt?

I searched in Google usually many posts are talking about how to open a new window and not indicating how to close the window. I found several posts in this website but most of them are using dialog window which is not considered in my software.
I make a UI, which contains a spin box and a button, to demonstrate my problem. I can type in a number equal or less than 5 in spin box. When I click the button, a number of new windows will show up and how many windows will show up is depending on the number in the spin box. If I change to the number in spin box then click the button, the original windows will be closed and new windows will be shown.
Fox example, first I type in "2" in spin box then click the button. Then 2 new windows will show up. If I change the number in spin box to 3 then click the button, the original 2 windows will be closed and 3 new windows will show up.
Here is my main program code:
from PyQt5.QtWidgets import QApplication, QMainWindow
from uitest_review import Ui_MainWindow # import the UI module
# set up a class for main window
class window(QMainWindow):
def __init__(self, parent=None):
super(window, self).__init__(parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.Open.clicked.connect(self.openwindow)
def openwindow(self):
windownum = self.ui.windownum.value()
print("open window num:", windownum)
opennewwindow = newwindow(self)
opennewwindow.show()
class newwindow(QMainWindow):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
if __name__ == "__main__":
app = QApplication([])
gui = window()
gui.show()
app.exec_()
Here is my UI code:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(816, 577)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName("gridLayout")
self.scrollArea = QtWidgets.QScrollArea(self.centralwidget)
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setObjectName("scrollArea")
self.scrollAreaWidgetContents = QtWidgets.QWidget()
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 796, 537))
self.scrollAreaWidgetContents.setObjectName(\
"scrollAreaWidgetContents")
self.verticalLayout = QtWidgets.QVBoxLayout(self.scrollAreaWidgetContents)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setObjectName("verticalLayout")
spacerItem = QtWidgets.QSpacerItem(20, 10, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
self.verticalLayout.addItem(spacerItem)
self.windownum = QtWidgets.QSpinBox(self.scrollAreaWidgetContents)
self.windownum.setMaximum(5)
self.windownum.setObjectName("windownum")
self.verticalLayout.addWidget(self.windownum)
self.groupBox = QtWidgets.QGroupBox(self.scrollAreaWidgetContents)
self.groupBox.setTitle("")
self.groupBox.setObjectName("groupBox")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.groupBox)
self.horizontalLayout.setObjectName("horizontalLayout")
spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem1)
self.Open = QtWidgets.QPushButton(self.groupBox)
font = QtGui.QFont()
font.setPointSize(14)
font.setBold(True)
font.setWeight(75)
self.Open.setFont(font)
self.Open.setObjectName("Open")
self.horizontalLayout.addWidget(self.Open)
spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem2)
self.verticalLayout.addWidget(self.groupBox)
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.gridLayout.addWidget(self.scrollArea, 0, 0, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.Open.setText(_translate("MainWindow", "Open"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
I create a new class (newwindow) in my main program and I can call this class to show a new window. But I cannot figure out how to detect how many windows is opened and how to close them. Does anyone can help me? Thank you so much.
I figured out by myself.
class window(QMainWindow):
def __init__(self, parent=None):
super(window, self).__init__(parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.Open.clicked.connect(self.openwindow)
self.openedwin = []
def openwindow(self):
windownum = self.ui.windownum.value()
if windownum != 0:
if self.openedwin != []:
for window in self.openedwin:
window.close()
for repeat in range(windownum):
opennewwindow = newwindow(self)
# print("opennewwindow:", opennewwindow)
self.openedwin.append(opennewwindow)
opennewwindow.show()
# print("self.openedwin:", self.openedwin)
class newwindow(QMainWindow):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
if __name__ == "__main__":
app = QApplication([])
gui = window()
gui.show()
app.exec_()
I add a list self.openedwin = [] to save all window objects. I can use "window object".close() command to close the window before opening new one.