PyQt5, how to open new window after click QButton - python

I clicked the button Platform Type, but Ui_Form doesn't show
I tried exec_() but Process finished with exit code -1073740791 (0xC0000409)
I want to open new QWidget window when clicked the button
Details: In Python, I want to make one more window when I press the button of the first widget. I tried to follow the other contents, but the program terminated with an error code. I would appreciate if you could let me know what the problem is.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Main_Widget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self._mutex = QtCore.QThread()
self.setupUi(Main_Widget)
def setupUi(self, Main_Widget):
Main_Widget.setObjectName('Main_Widget')
Main_Widget.resize(1272, 640)
self.All_GroupBox = QtWidgets.QGroupBox(Main_Widget)
self.All_GroupBox.setGeometry(QtCore.QRect(20, 10, 1231, 611))
font = QtGui.QFont()
self.All_GroupBox.setFont(font)
self.All_GroupBox.setObjectName('All_GroupBox')
self.verticalLayoutWidget = QtWidgets.QWidget(self.All_GroupBox)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(20, 30, 261, 331))
self.verticalLayoutWidget.setObjectName('verticalLayoutWidget')
self.Button_VerticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.Button_VerticalLayout.setContentsMargins(0, 0, 0, 0)
self.Button_VerticalLayout.setObjectName('Button_VerticalLayout')
self.PlatformType_Button = QtWidgets.QPushButton(self.verticalLayoutWidget)
self.PlatformType_Button.setMinimumSize(QtCore.QSize(0, 45))
self.PlatformType_Button.setObjectName('PlatformType_Button')
self.Button_VerticalLayout.addWidget(self.PlatformType_Button)
def PlatformType_Clicked(self):
dialog = Ui_Form(self)
self.dialogs.append(dialog)
dialog.show()
dialog.exec_()
class Ui_Form(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Ui_Form, self).__init__(parent)
def setupUi(self, Form):
Form.setObjectName('Form')
Form.resize(422, 190)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
Main_Widget = QtWidgets.QWidget()
ui = Ui_Main_Widget()
Main_Widget.show()
app.exec_()

Try it:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Main_Widget(QtWidgets.QWidget):
# def __init__(self):
# super().__init__()
# self._mutex = QtCore.QThread()
# self.setupUi(Main_Widget)
def setupUi(self, Main_Widget):
Main_Widget.setObjectName('Main_Widget')
Main_Widget.resize(1272, 640)
self.All_GroupBox = QtWidgets.QGroupBox(Main_Widget)
self.All_GroupBox.setGeometry(QtCore.QRect(20, 10, 1231, 611))
font = QtGui.QFont()
self.All_GroupBox.setFont(font)
self.All_GroupBox.setObjectName('All_GroupBox')
self.verticalLayoutWidget = QtWidgets.QWidget(self.All_GroupBox)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(20, 30, 261, 331))
self.verticalLayoutWidget.setObjectName('verticalLayoutWidget')
self.Button_VerticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.Button_VerticalLayout.setContentsMargins(0, 0, 0, 0)
self.Button_VerticalLayout.setObjectName('Button_VerticalLayout')
self.PlatformType_Button = QtWidgets.QPushButton("PlatformType_Button", self.verticalLayoutWidget)
self.PlatformType_Button.setMinimumSize(QtCore.QSize(0, 45))
self.PlatformType_Button.setObjectName('PlatformType_Button')
# +++
self.PlatformType_Button.clicked.connect(Main_Widget.PlatformType_Clicked) # +++
self.Button_VerticalLayout.addWidget(self.PlatformType_Button)
# def PlatformType_Clicked(self):
# dialog = Ui_Form(self)
# self.dialogs.append(dialog)
# dialog.show()
# dialog.exec_()
class Ui_Form(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Ui_Form, self).__init__(parent)
def setupUi(self, Form):
Form.setObjectName('Form')
Form.resize(422, 190)
class MyWindow(QtWidgets.QWidget): # +++
def __init__(self):
super().__init__()
self.ui = Ui_Main_Widget()
self.ui.setupUi(self)
# +++
def PlatformType_Clicked(self):
self.dialog = Ui_Form() # --- self
# self.dialogs.append(dialog)
self.dialog.show()
# self.dialog.exec_()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = MyWindow()
w.show()
sys.exit(app.exec_())

hide() and show() method you can use multiple dialog what ever you want,...
def PlatformType_Clicked(self):
dialog.hide()
dialog1.show()

Related

Pushbutton is not being responsive

i'm pretty new to python and PyQt5.
My goal is to use a "Push Button" to move to the next widget in the "Stacked Layout". However, it's not being responsive, and it appears that it won't enter the function in order to move on to the next widget.
I have no idea wether its the inheritance i've messed up on, or something else. Any guidance is really appreciated. Thank you!
from PyQt5 import QtCore, QtGui, QtWidgets
class Menu(QtWidgets.QWidget):
def setupUI(self, Main):
Main.setObjectName("Main")
Main.setFixedSize(900, 500)
self.width = 900
self.height = 500
self.setFixedSize(self.width, self.height)
self.menu = QtWidgets.QStackedLayout()
self.welcomeMenu = QtWidgets.QWidget()
self.mainMenu = QtWidgets.QWidget()
self.welcomeUi()
self.menuUi()
self.menu.addWidget(self.welcomeMenu)
self.menu.addWidget(self.mainMenu)
def welcomeUi(self):
#Button for entering portal
self.entrBtn = QtWidgets.QPushButton(self.welcomeMenu)
self.entrBtn.setGeometry(QtCore.QRect(25,150,200,50))
self.entrBtn.setText("To the menu screen!")
#Having welcome text
self.welcomeText = QtWidgets.QLabel(self.welcomeMenu)
self.welcomeText.setGeometry(QtCore.QRect(30, 120, 480, 200))
self.welcomeText.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.welcomeText.setText("Welcome!")
def menuUi(self):
self.text = QtWidgets.QLabel(self.mainMenu)
self.text.setGeometry(QtCore.QRect(30, 120, 480, 200))
self.text.setText("test")
class Main(QtWidgets.QMainWindow, Menu):
def __init__(self):
super(Main, self).__init__()
self.setupUI(self)
self.entrBtn.clicked.connect(self.menuWindow)
def menuWindow(self):
self.menu.setCurrentWidget(self.mainMenu)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
m = Main()
sys.exit(app.exec_())
The problem is simple: QLabel is on top of the button so it will block all mouse events. The simple solution is to put QPushButton on QLabel using raise_():
# ...
self.welcomeText.setText("Welcome!")
self.entrBtn.raise_()
But that solves the superficial problem, you have other bigger problem: You should not inherit from 2 QWidget, also the Main is not shown. It is better to rewrite the code as follows:
from PyQt5 import QtCore, QtGui, QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.welcomeMenu = QtWidgets.QWidget()
self.mainMenu = QtWidgets.QWidget()
self.fill_welcomeUi()
self.fill_menuUi()
self.stacked_lay = QtWidgets.QStackedLayout()
self.stacked_lay.addWidget(self.welcomeMenu)
self.stacked_lay.addWidget(self.mainMenu)
central_widget = QtWidgets.QWidget()
self.setCentralWidget(central_widget)
central_widget.setLayout(self.stacked_lay)
self.entrBtn.clicked.connect(self.menuWindow)
self.resize(640, 480)
def menuWindow(self):
self.stacked_lay.setCurrentWidget(self.mainMenu)
def fill_welcomeUi(self):
#Button for entering portal
self.entrBtn = QtWidgets.QPushButton(self.welcomeMenu)
self.entrBtn.setGeometry(QtCore.QRect(25,150,200,50))
self.entrBtn.setText("To the menu screen!")
#Having welcome text
self.welcomeText = QtWidgets.QLabel(self.welcomeMenu)
self.welcomeText.setGeometry(QtCore.QRect(30, 120, 480, 200))
self.welcomeText.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.welcomeText.setText("Welcome!")
self.entrBtn.raise_()
def fill_menuUi(self):
self.text = QtWidgets.QLabel(self.mainMenu)
self.text.setGeometry(QtCore.QRect(30, 120, 480, 200))
self.text.setText("test")
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
m = MainWindow()
m.show()
sys.exit(app.exec_())

QtabWidget and QMainWindow in one class

Is there a way to define the menubar in a QtabWidget class ?
I wrote a code for a destopapplication with pyqt5 and python 3.6. I would like to set the manuBar in the same class as the Tabs but my code returns qtabwidget has no attribute QMainWindow.
Here is my code:
import sys
from PyQt5 import QtWidgets, QtCore, QtPrintSupport, QtGui
from PyQt5.QtWidgets import *
class main_window(QTabWidget):
def __init__(self, parent=None):
super(QTabWidget, self).__init__(parent)
self.setGeometry(50, 50, 1100, 750)
self.setWindowTitle("Programm") #
self.centralWidget = QtWidgets.QWidget()
self.tabWidget = QtWidgets.QTabWidget(self.centralWidget)
self.tabWidget.setGeometry(QtCore.QRect(10, 10, 1200, 1000))
open_new_file = QAction('New', self)
mainMenu = self.menuBar()
fileMenu = mainMenu.addMenu('Projekt')
fileMenu.addAction(open_new_file)
self.table_widget = MyTableWidget(self)
self.setCentralWidget(self.table_widget)
self.show()
self.tab_v1 = QtWidgets.QWidget()
self.addTab(self.tab_v1, "Tab 1")
self.tab_v2 = QtWidgets.QWidget()
self.addTab(self.tab_v2, "Tab 2")
self.openFile = QPushButton("Choose Tab ", self.tab_v1)
self.openFile.setGeometry(QtCore.QRect(700, 25, 200, 30))
def main():
app = QApplication(sys.argv)
ex = main_window()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
QTabWidget can not have a QMenuBar, what you have to do is put the centralwidget of a QMainWindow to the QTabWidget.
import sys
from PyQt5 import QtCore, QtWidgets
class Main_window(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(Main_window, self).__init__(parent)
self.setGeometry(50, 50, 1100, 750)
self.setWindowTitle("Programm")
open_new_file = QtWidgets.QAction('New', self)
mainMenu = self.menuBar()
fileMenu = mainMenu.addMenu('Projekt')
fileMenu.addAction(open_new_file)
self.tabWidget = QtWidgets.QTabWidget()
self.setCentralWidget(self.tabWidget)
self.tab_v1 = QtWidgets.QWidget()
self.tabWidget.addTab(self.tab_v1, "Tab 1")
self.openFile =QtWidgets.QPushButton("Choose Tab ", self.tab_v1)
self.openFile.setGeometry(QtCore.QRect(700, 25, 200, 30))
self.tab_v2 = QtWidgets.QWidget()
self.tabWidget.addTab(self.tab_v2, "Tab 2")
def main():
app = QtWidgets.QApplication(sys.argv)
ex = Main_window()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()

PySide/PyQT5: How to emit signals from a QGraphicsItem?

I want to emit a signal from a QGraphicsItem when it is doubled-clicked, in order to change a widget in the main window. The graphics-scene/-item does not provide an emit() method, but I was just wondering if there is an alternate way to do this. The code below has a function within a QGraphicsView class that will print to the terminal when an item is double-clicked. How can I make that into a slot/signal instead (if QGraphicsItem does not support signal/slots)?
import sys
from PySide.QtCore import *
from PySide.QtGui import *
class MyFrame(QGraphicsView):
def __init__( self, parent = None ):
super(MyFrame, self).__init__(parent)
scene = QGraphicsScene()
self.setScene(scene)
self.setFixedSize(500, 500)
pen = QPen(QColor(Qt.green))
brush = QBrush(pen.color().darker(150))
item = scene.addEllipse(0, 0, 45, 45, pen, brush)
item.setPos(0,0)
def mouseDoubleClickEvent(self, event):
print("Circle Clicked!")
# this double click event prints to terminal but how to setup
# signal/slot to update the QWidget QLabel text instead?
class Example(QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
hbox = QHBoxLayout(self)
top = QLabel("Double Click Green Circle (Howto change this QWidget Label with signals?)")
bottom = MyFrame()
splitter = QSplitter(Qt.Vertical)
splitter.addWidget(top)
splitter.addWidget(bottom)
hbox.addWidget(splitter)
self.setLayout(hbox)
self.setGeometry(0, 0, 500, 600)
self.show()
def main():
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Below is a simple example showing one way to emit signals from a graphics-item. This defines a custom signal on a subclass of QGraphicsScene and then uses the scene() method of graphics-items to emit it:
import sys
from PySide import QtCore, QtGui
class GraphicsScene(QtGui.QGraphicsScene):
itemDoubleClicked = QtCore.Signal(object)
class GraphicsRectangle(QtGui.QGraphicsRectItem):
def mouseDoubleClickEvent(self, event):
self.scene().itemDoubleClicked.emit(self)
class Window(QtGui.QWidget):
def __init__(self):
super(Window, self).__init__()
self.view = QtGui.QGraphicsView()
self.scene = GraphicsScene(self)
self.view.setScene(self.scene)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.view)
for i in range(1, 4):
self.scene.addItem(GraphicsRectangle(50 * i, 50 * i, 20, 20))
self.scene.itemDoubleClicked.connect(self.handleItemDoubleClicked)
def handleItemDoubleClicked(self, item):
print(item.boundingRect())
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = Window()
window.setGeometry(600, 100, 300, 200)
window.show()
sys.exit(app.exec_())
UPDATE:
Below is a an example based on the code in your question. The basic idea is the same: define a custom signal on an available QObject (the graphics-view in this case), and use that to emit the double-click notification.
import sys
from PySide.QtCore import *
from PySide.QtGui import *
class MyFrame(QGraphicsView):
itemDoubleClicked = Signal(object)
def __init__(self, parent=None):
super(MyFrame, self).__init__(parent)
scene = QGraphicsScene()
self.setScene(scene)
self.setFixedSize(500, 500)
for i, color in enumerate('red blue green'.split()):
pen = QPen(QColor(color))
brush = QBrush(pen.color().darker(150))
item = scene.addEllipse(i * 50, i * 50, 45, 45, pen, brush)
item.setData(0, color.upper())
def mouseDoubleClickEvent(self, event):
item = self.itemAt(event.pos())
if item is not None:
self.itemDoubleClicked.emit(item)
class Example(QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
hbox = QHBoxLayout(self)
top = QLabel('Double Click a Circle')
bottom = MyFrame()
bottom.itemDoubleClicked.connect(
lambda item, top=top:
top.setText('Double Clicked: %s' % item.data(0)))
splitter = QSplitter(Qt.Vertical)
splitter.addWidget(top)
splitter.addWidget(bottom)
hbox.addWidget(splitter)
self.setLayout(hbox)
self.setGeometry(0, 0, 500, 600)
self.show()
def main():
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()

Clear QLineEdit on click event

I am using the given code, I want the user to enter text in the QLineEdit widget, press the Copy! button and see the inputted text replace the 'N/A' label. My questions is: following this procedure, how can I clear the text inputted in the QLineEdit widget with a simple mouse click?
From what I read (this, this and this) it seems like I need to reimplement focusInEvent() in a new class extending QLineEdit. My problem is that the code for my GUI has been imported from Qt Designer using pyuic5 and the examples cited above don't seem to take this in consideration.
Here is my code:
from PyQt5.QtWidgets import *
import sys
import QLineEdit_test
class MainWindow(QMainWindow, QLineEdit_test.Ui_QLineEdit_test):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
self.copy_button.clicked.connect(self.copy_and_print)
def copy_and_print(self):
self.label.setText(self.lineEdit.text())
def main():
app = QApplication(sys.argv)
form = MainWindow()
form.show()
app.exec_()
if __name__ == "__main__":
main()
Here is my converted .ui file:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_QLineEdit_test(object):
def setupUi(self, QLineEdit_test):
QLineEdit_test.setObjectName("QLineEdit_test")
QLineEdit_test.resize(300, 200)
QLineEdit_test.setMaximumSize(QtCore.QSize(300, 200))
self.centralwidget = QtWidgets.QWidget(QLineEdit_test)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout_2 = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout_2.setObjectName("gridLayout_2")
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setObjectName("gridLayout")
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setMaximumSize(QtCore.QSize(120, 16777215))
self.lineEdit.setObjectName("lineEdit")
self.gridLayout.addWidget(self.lineEdit, 0, 0, 1, 1)
self.copy_button = QtWidgets.QPushButton(self.centralwidget)
self.copy_button.setObjectName("copy_button")
self.gridLayout.addWidget(self.copy_button, 1, 0, 1, 1)
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setMaximumSize(QtCore.QSize(200, 20))
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName("label")
self.gridLayout.addWidget(self.label, 2, 0, 1, 1)
self.gridLayout_2.addLayout(self.gridLayout, 0, 0, 1, 1)
QLineEdit_test.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(QLineEdit_test)
self.menubar.setGeometry(QtCore.QRect(0, 0, 300, 22))
self.menubar.setObjectName("menubar")
QLineEdit_test.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(QLineEdit_test)
self.statusbar.setObjectName("statusbar")
QLineEdit_test.setStatusBar(self.statusbar)
self.retranslateUi(QLineEdit_test)
QtCore.QMetaObject.connectSlotsByName(QLineEdit_test)
def retranslateUi(self, QLineEdit_test):
_translate = QtCore.QCoreApplication.translate
QLineEdit_test.setWindowTitle(_translate("QLineEdit_test", "MainWindow"))
self.copy_button.setText(_translate("QLineEdit_test", "Copy!"))
self.copy_button.setShortcut(_translate("QLineEdit_test", "Return"))
self.label.setText(_translate("QLineEdit_test", "N/A"))
The solution is to promote QtDesigner use our custom QLineEdit where we implement the signal clicked with the help of mousePressEvent, this class will be called ClickableLineEdit and the file will be called ClickableLineEdit.py.
ClickableLineEdit.py
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import QLineEdit
class ClickableLineEdit(QLineEdit):
clicked = pyqtSignal()
def mousePressEvent(self, event):
self.clicked.emit()
QLineEdit.mousePressEvent(self, event)
To promote it, the following structure will be considered:
.
├── ClickableLineEdit.py
├── main.py
├── your.ui
└── QLineEdit_test.py
Open the design with Qt Designer and right click on the QLineEdit and select Promote to ...:
A menu will open and place the following
then press and Promote. Then we generate the code again.
Then we connect the signal to clear:
class MainWindow(QMainWindow, QLineEdit_test.Ui_QLineEdit_test):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
self.copy_button.clicked.connect(self.copy_and_print)
self.lineEdit.clicked.connect(self.lineEdit.clear)
def copy_and_print(self):
self.label.setText(self.lineEdit.text())
Update:
PySide2:
from PySide2 import QtCore, QtWidgets
class ClickableLineEdit(QtWidgets.QLineEdit):
clicked = QtCore.Signal()
def mousePressEvent(self, event):
super(ClickableLineEdit, self).mousePressEvent(event)
self.clicked.emit()
class App(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.lineedit = ClickableLineEdit()
self.lineedit.clicked.connect(self.lineedit.clear)
lay = QtWidgets.QVBoxLayout(self)
lay.addWidget(self.lineedit)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication.instance()
if app is None:
app = QtWidgets.QApplication(sys.argv)
ex = App()
ex.show()
sys.exit(app.exec_())
def __init__(self, *args, **kwargs):
QWidget.__init__(self, *args, **kwargs)
layout = QGridLayout()
self.setLayout(layout)
self.lineedit = QLineEdit()
self.lineedit.returnPressed.connect(self.press)
layout.addWidget(self.lineedit, 0, 0)
def press(self):
print("Hi World")
self.lineedit.clear()
If someone is still looking for a way to do this, but you only want the Line edit to be cleared when it first clicked and not every time it is clicked, you can do so without using variables like this :
def init_UI(self):
self.text_input = QLineEdit('Type your name')
self.text_input.mousePressEvent = self._mousePressEvent
def _mousePressEvent(self, event):
self.text_input.clear()
self.text_input.mousePressEvent = None
This way the _mousePressEvent gets called only once
I have an optional solution in one line:
self.lineEdit.mouseReleaseEvent = self.copy_and_print
Make sure you are receiving two parameters in your function (self,event)
I hope I helped you
Full post: https://wiki.python.org/moin/PyQt/Making%20non-clickable%20widgets%20clickable
Use mousePressEvent of QLineEdit to detect mouse click. To clear the text use clear() method or setText() method of QLineEdit.
#called when ever mouse is pressed
def mousePressed(self, event):
print('mouse pressed')
self.lineEdit=QLineEdit("Awesome day")#from PyQt5.QtWidget import QLineEdit
self.lineEdit.mousePressEvent = self.mousePressed
Example program :
import sys
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QApplication, QLineEdit
class ButtonPanel(QWidget):
def __init__(self, heading):
self.initUI(heading)
def initUI(self, heading):
super().__init__()
self.layout = QHBoxLayout()
self.lineEdit = QLineEdit(heading)
#self.lineEdit.setReadOnly(True)
self.lineEdit.returnPressed.connect(self.returnPressed)
self.lineEdit.mousePressEvent = self.mousePressed
self.delete = QPushButton("D")
self.layout.addWidget(self.lineEdit)
self.layout.addWidget(self.delete)
self.setLayout(self.layout)
self.show()
#called when mouse is clicked
def mousePressed(self, event):
self.lineEdit.clear() #text is cleared
//self.lineEdit.setText("") #this way we can also clear the text
print('mouse pressed')
//called when return key is pressed
def returnPressed(self):
print('return pressed')
if __name__ == "__main__":
app = QApplication(sys.argv)
b = ButtonPanel("Awesome")
sys.exit(app.exec())
Output :

How to add a tab to QTabWidget using the button on the form?

I decided to write a visual form for my script.
The idea is to have a button that will add new tabs to QTabWidget. It does not work and I can not find a good example. I use PyQt5. Here's a piece of what I've tried:
import sys
from PyQt5.QtGui import QIcon
from PyQt5 import QtCore, QtWidgets
class mainForm(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.runUi()
def runUi(self):
self.resize(250, 150)
self.move(300, 300)
self.setWindowTitle('Let\'s Rock!')
self.setWindowIcon(QIcon('icon.png'))
self.setMaximumSize(QtCore.QSize(560, 522))
self.setMinimumSize(QtCore.QSize(560, 522))
groupBoxGD = QtWidgets.QGroupBox('Соединение с ГД', self)
groupBoxGD.setGeometry(QtCore.QRect(10, 10, 541, 151))
hrLWGDLink = QtWidgets.QWidget(groupBoxGD)
hrLWGDLink.setGeometry(QtCore.QRect(10, 10, 521, 31))
hrLGD = QtWidgets.QHBoxLayout(hrLWGDLink)
hrLGD.setContentsMargins(0, 0, 0, 0)
btnAddTab = QtWidgets.QPushButton(hrLWGDLink)
btnAddTab.setText('Add tab')
hrLGD.addWidget(btnAddTab)
tabWidget = QtWidgets.QTabWidget(groupBoxGD)
tabWidget.setGeometry(QtCore.QRect(10, 170, 541, 351))
btnAddTab.clicked.connect(self.addProjectTab)
self.show()
def addProjectTab(self):
tab = QtWidgets.QWidget()
#how add tab at this line?
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
ui = mainForm()
sys.exit(app.exec_())
You have to use the addTab() function, but to do so from another class the QTabWidget object must be a member of the class. Also I made some changes in the design because the button was on the QTabWidget, covering the tabs.
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
class mainForm(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.runUi()
def runUi(self):
self.resize(250, 150)
self.move(300, 300)
self.setWindowTitle('Let\'s Rock!')
self.setWindowIcon(QtGui.QIcon('icon.png'))
self.setMaximumSize(QtCore.QSize(560, 522))
self.setMinimumSize(QtCore.QSize(560, 522))
layout = QtWidgets.QVBoxLayout(self)
groupBoxGD = QtWidgets.QGroupBox('Соединение с ГД', self)
layout2 = QtWidgets.QVBoxLayout(groupBoxGD)
hrLWGDLink = QtWidgets.QWidget(groupBoxGD)
hrLGD = QtWidgets.QVBoxLayout(hrLWGDLink)
hrLGD.setContentsMargins(0, 0, 0, 0)
btnAddTab = QtWidgets.QPushButton(hrLWGDLink)
btnAddTab.setText('Add tab')
hrLGD.addWidget(btnAddTab)
self.tabWidget = QtWidgets.QTabWidget(hrLWGDLink)
hrLGD.addWidget(self.tabWidget)
layout2.addWidget(hrLWGDLink)
layout.addWidget(groupBoxGD)
btnAddTab.clicked.connect(self.addProjectTab)
def addProjectTab(self):
tab = QtWidgets.QWidget()
self.tabWidget.addTab(tab, "tab")
app = QtWidgets.QApplication(sys.argv)
w = mainForm()
w.show()
sys.exit(app.exec_())
Screenshot:

Categories

Resources