How to emit signal when a combo box in table changes? - python

How can I emit a signal (or for now print the text) whenever the text from any QComboBox changes? A new QComboBox is created in both columns every time a row is added to a QTableWidget. Eventually, that signal will trigger a redraw of a plot.
Right now, I'm able to print the text from a QComboBox that already exists with a specific instance name, but I don't know how to do it when combo boxes are created dynamically in the table.
Main code:
import sys
from PyQt5.QtWidgets import (
QMainWindow,
QApplication,
QComboBox,
)
from cb_in_tables import Ui_MainWindow
class MyWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.comboBox.addItems(['', '1', '2', '3'])
self.ui.pushButton.clicked.connect(self.addRow)
self.ui.comboBox.currentTextChanged.connect(self.printComboBoxText)
def printComboBoxText(self, text):
print(text)
def addRow(self):
"""Add new row to data table and populate with widgets."""
# Insert row
rowPos = self.ui.tableWidget.rowCount()
self.ui.tableWidget.insertRow(rowPos)
x_combobox = QComboBox()
x_combobox.addItems(['', 'A', 'B', 'C'])
self.ui.tableWidget.setCellWidget(rowPos, 0, x_combobox)
y_combobox = QComboBox()
y_combobox.addItems(['', 'X', 'Y', 'Z'])
self.ui.tableWidget.setCellWidget(rowPos, 1, y_combobox)
if __name__ == "__main__":
app = QApplication(sys.argv)
main = MyWindow()
main.show()
sys.exit(app.exec_())
UI file:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'cb_in_tables.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(291, 299)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget.setGeometry(QtCore.QRect(30, 60, 231, 161))
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(2)
self.tableWidget.setRowCount(0)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(1, item)
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(30, 20, 113, 32))
self.pushButton.setObjectName("pushButton")
self.comboBox = QtWidgets.QComboBox(self.centralwidget)
self.comboBox.setGeometry(QtCore.QRect(160, 20, 104, 31))
self.comboBox.setObjectName("comboBox")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 291, 24))
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"))
item = self.tableWidget.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "X"))
item = self.tableWidget.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "Y"))
self.pushButton.setText(_translate("MainWindow", "Add Row"))
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_())

Nothing changes:
x_combobox.currentTextChanged.connect(self.printComboBoxText)
y_combobox.currentTextChanged.connect(self.printComboBoxText)

Related

Start a QT Thread when button is clicked

This is a sample code with just a push button and a textedit, i need to write line x line using a loop in a textedit when button is clicked.
The problem is that i need to implement threads because without them the program crashes or it doesn't write line x line, but all together when the loop ends;
and i need to implement in my application a textedit that shows info while the program loads "something".
So my question is, how to rewrite this code using threads to write in textedit when button is clicked?
The method i should run when the button is clicked is "write"
it should work like a print inside a for loop , it would print not all at once
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(640, 480)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.textEdit = QtWidgets.QTextEdit(self.centralwidget)
self.textEdit.setGeometry(QtCore.QRect(150, 220, 321, 71))
self.textEdit.setObjectName("textEdit")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(240, 100, 75, 23))
self.pushButton.setObjectName("pushButton")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 640, 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"))
self.pushButton.setText(_translate("MainWindow", "PushButton"))
self.pushButton.clicked.connect(self.write)
def write(self):
string=""
for i in range(1000):
string="\n"+str(i)
self.textEdit.insertPlainText(string)
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
First of all it is recommended not to modify the class generated by Qt Designer so you must regenerate the file and assume that it is called mainwindow.py: pyuic5 your_file.ui -o mainwindow.py -x.
Considering the above, the logic is to generate the information in another thread and send it to the GUI to modify it:
main.py
import threading
from PyQt5 import QtCore, QtGui, QtWidgets
from mainwindow import Ui_MainWindow
class WriterWorker(QtCore.QObject):
textChanged = QtCore.pyqtSignal(str)
def start(self):
threading.Thread(target=self._execute, daemon=True).start()
def _execute(self):
string = ""
for i in range(1000):
string = "\n"+str(i)
self.textChanged.emit(string)
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
self.writer_worker = WriterWorker()
self.writer_worker.textChanged.connect(self.on_text_changed)
self.pushButton.clicked.connect(self.writer_worker.start)
#QtCore.pyqtSlot(str)
def on_text_changed(self, text):
self.textEdit.insertPlainText(text)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())

Expand item in QTreeView with QFileSystemModel

I need to going to some directory when user click on button.
User enter path in QInputDialog (for example /mnt/data/Music on linux), and program go to this directory, like M-c in Midnight Commander or cd in ranger, but i don't know how i can do this... I already know all the documentation by heart
main.py
import sys
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtWidgets import QMainWindow, QInputDialog
import exampleQTV
class PyMap(QMainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.search.clicked.connect(self.searchAction)
def searchAction(self):
text, ok = QInputDialog.getText(self, "Go to", "Enter path")
if ok:
path = text.split("/")
for item in path:
if item != "":
print("ITEM:", item)
self.leftView.keyboardSearch(item)
self.leftView.setExpanded(self.leftView.currentIndex(), True)
print("currentIndex():",self.leftView.model.filePath(self.leftView.currentIndex()))
child = self.leftView.currentIndex().child(0,0)
print("child:", self.leftView.model.filePath(child))
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName("gridLayout")
self.leftView = exampleQTV.exampleQTV()
self.leftView.setObjectName("leftView")
self.gridLayout.addWidget(self.leftView, 1, 0, 1, 1)
self.search = QtWidgets.QPushButton(self.centralwidget)
self.search.setObjectName("select")
self.gridLayout.addWidget(self.search, 0, 0, 1, 2)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 22))
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"))
self.search.setText(_translate("MainWindow", "Search"))
def main():
app = QtWidgets.QApplication(sys.argv)
window = PyMap()
window.show()
app.exec_()
if __name__ == '__main__':
main()
exampleQTV.py
from PyQt5.QtWidgets import QTreeView, QFileSystemModel
from PyQt5.QtCore import QDir
class exampleQTV(QTreeView):
def __init__(self):
QTreeView.__init__(self)
self.model = QFileSystemModel()
self.model.setRootPath(QDir.rootPath())
self.setModel(self.model)
self.eventCalled = False
self.requestForEscape = False
self.setColumnHidden(1, True)
self.setColumnHidden(2, True)
self.setColumnHidden(3, True)
self.expandAll()
If you want an item to be expanded your ancestors must be expanded, in the following code you implement that logic:
import sys
from PyQt5 import QtCore, QtWidgets
def expandPath(index, view):
if not index.isValid():
return
indexes = []
ix = index
while ix.isValid():
indexes.insert(0, ix)
ix = ix.parent()
for ix in indexes:
view.expand(ix)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
model = QtWidgets.QFileSystemModel()
model.setRootPath(QtCore.QDir.rootPath())
view = QtWidgets.QTreeView()
view.setModel(model)
view.setRootIndex(model.index(QtCore.QDir.rootPath()))
doc_directory = QtCore.QStandardPaths.writableLocation(
QtCore.QStandardPaths.DocumentsLocation
)
ix = model.index(doc_directory)
expandPath(ix, view)
view.resize(640, 480)
for i in (1, 2, 3):
view.setColumnHidden(i, True)
view.show()
sys.exit(app.exec_())

Switch button in pyqt

Is it possible to create a switch button with pyqt5?
I'm designing a filtering tool in python using pyqt5. The user is supposed to be able to apply a filter or its complement on some data and even combine filters.
I display possible filters in qtablewidget where the user can choose filters to apply using checkboxes. In each row, checkboxes are exclusives i.e. the user can not select a filter and its complement at the same time.
But the problem is that once we select a checkbox in a row, we cannot deselect it unless we select its opposite.
In fact, when the filters are just loaded , all the boxes are unchecked (they are empty in a way) so I can choose which filter to apply but when I want to choose an other filter, one of the boxes of the precedent filter still checked (either box Filter or box Complement is checked) and I can not switch it off.
That's why I thought about adding a switch button in each row to disable a filter. By doing this I will be able to take in consideration or not the checked attribute.
Here is an example of what I want :
Below an reproductible example
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(550, 350)
MainWindow.setMinimumSize(QtCore.QSize(550, 350))
MainWindow.setMaximumSize(QtCore.QSize(550, 350))
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget.setGeometry(QtCore.QRect(20, 20, 500, 200))
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(3)
self.tableWidget.setRowCount(0)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(1, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(2, item)
self.pushButton_Save = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_Save.setGeometry(QtCore.QRect(120, 250, 100, 50))
self.pushButton_Save.setMinimumSize(QtCore.QSize(100, 50))
self.pushButton_Save.setMaximumSize(QtCore.QSize(100, 50))
self.pushButton_Save.setObjectName("pushButton_Save")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 550, 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"))
item = self.tableWidget.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "Name"))
item = self.tableWidget.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "Filter"))
item = self.tableWidget.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", "complement"))
self.pushButton_Save.setText(_translate("MainWindow", "Save"))
self.pushButton_Save.clicked.connect(self.bindSave)
def bindSave(self):
numRows = self.tableWidget.rowCount()
self.tableWidget.insertRow(numRows)
groupButton = QtWidgets.QButtonGroup(self.tableWidget)
groupButton.setExclusive(True)
it1 = QtWidgets.QTableWidgetItem("filter "+str(numRows))
self.tableWidget.setItem(numRows, 0, it1)
ch_bx1 = QtWidgets.QCheckBox()
groupButton.addButton(ch_bx1)
self.tableWidget.setCellWidget(numRows, 1, ch_bx1)
ch_bx2 = QtWidgets.QCheckBox()
groupButton.addButton(ch_bx2)
self.tableWidget.setCellWidget(numRows, 2, ch_bx2)
if __name__ == "__main__":
if not QtWidgets.QApplication.instance():
app = QtWidgets.QApplication(sys.argv)
else:
app = QtWidgets.QApplication.instance()
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
Like others have suggested, you could enable/disable filters by adding a third column to the table and setting each item widget in this column to a like you did for ch_box1 and ch_box2. You can use slots and signals to manipulate the check buttons (for example enable/disable them depending on the state of the switch).
To create custom switches like in the picture in the OP, you could sub-class QPushButton and overriding paintEvent, e.g. (note that I've omitted the code that was the same as the code in the reproducable example in the original post)
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt, QRect
import sys
class MySwitch(QtWidgets.QPushButton):
def __init__(self, parent = None):
super().__init__(parent)
print('init')
self.setCheckable(True)
self.setMinimumWidth(66)
self.setMinimumHeight(22)
def paintEvent(self, event):
label = "ON" if self.isChecked() else "OFF"
bg_color = Qt.green if self.isChecked() else Qt.red
radius = 10
width = 32
center = self.rect().center()
painter = QtGui.QPainter(self)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
painter.translate(center)
painter.setBrush(QtGui.QColor(0,0,0))
pen = QtGui.QPen(Qt.black)
pen.setWidth(2)
painter.setPen(pen)
painter.drawRoundedRect(QRect(-width, -radius, 2*width, 2*radius), radius, radius)
painter.setBrush(QtGui.QBrush(bg_color))
sw_rect = QRect(-radius, -radius, width + radius, 2*radius)
if not self.isChecked():
sw_rect.moveLeft(-width)
painter.drawRoundedRect(sw_rect, radius, radius)
painter.drawText(sw_rect, Qt.AlignCenter, label)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
....
self.tableWidget.setColumnCount(4)
....
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(3, item)
...
def retranslateUi(self, MainWindow):
...
item = self.tableWidget.horizontalHeaderItem(3)
item.setText(_translate("MainWindow", "status"))
def bindSave(self):
...
ch_bx3 = MySwitch()
ch_bx3.setChecked(True)
ch_bx3.clicked.connect(ch_bx1.setEnabled)
ch_bx3.clicked.connect(ch_bx2.setEnabled)
self.tableWidget.setCellWidget(numRows, 3, ch_bx3)
if __name__ == "__main__":
if not QtWidgets.QApplication.instance():
app = QtWidgets.QApplication(sys.argv)
else:
app = QtWidgets.QApplication.instance()
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
app.exec()
Screenshot:

How to passing value from main to dialog

I'm newbie for using Pyqt5.
I use qtdesigner for building GUI.
I have MainWindow for passing value to dialogwindow
I want to LineEdit( in dialogwindow) show value after user input and click button (in MainWindow)
I try
self.ui = Ui_Dialog(self,data)
but it doesn't work
My code mainpage
MainWindow.py
from PyQt5 import QtCore, QtGui, QtWidgets
from dialog import Ui_Dialog
class Ui_MainWindow(object):
def openDialog(self):
data = self.lineEdit.text()
self.window = QtWidgets.QDialog()
self.ui = Ui_Dialog(self,data)
self.ui.setupUi(self.window)
# MainWindow.hide()
self.window.show()
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(505, 236)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(120, 40, 91, 16))
self.label.setObjectName("label")
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(290, 40, 113, 22))
self.lineEdit.setObjectName("lineEdit")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(190, 110, 93, 28))
self.pushButton.clicked.connect(self.openDialog)
self.pushButton.setObjectName("pushButton")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 505, 26))
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"))
self.label.setText(_translate("MainWindow", "Passing Value"))
self.pushButton.setText(_translate("MainWindow", "Send"))
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_())
Dialog code.py
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(577, 253)
self.lineEdit = QtWidgets.QLineEdit(Dialog)
self.lineEdit.setGeometry(QtCore.QRect(260, 100, 113, 22))
self.lineEdit.setObjectName("lineEdit")
self.label = QtWidgets.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(180, 100, 55, 16))
self.label.setObjectName("label")
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.label.setText(_translate("Dialog", "Value"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
advice me plz
Thank you,
Mint
PyQt recommends not modifying the .py generated by pyuic and Qt Designer but creating another file that uses that class to fill a widget so I recommend regenerating the MainWindow.py and dialog.py files.
Now create a main.py where we inherit the appropriate class by setting a constructor with the requirement:
main.py
from PyQt5 import QtCore, QtGui, QtWidgets
from dialog import Ui_Dialog
from MainWindow import Ui_MainWindow
class Dialog(QtWidgets.QDialog, Ui_Dialog):
def __init__(self, text, parent=None):
super(Dialog, self).__init__(parent)
self.setupUi(self)
self.lineEdit.setText(text)
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
self.pushButton.clicked.connect(self.openDialog)
def openDialog(self):
data = self.lineEdit.text()
w = Dialog(data)
w.exec_()
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())

How to get the objectName of MDI Area subwindow?

I have tried
self.mdiArea.activeSubWindow().objectName
self.mdiArea.activeSubWindow().objectName()
But neither of them gave me the object name I set:
self.subwindow.setObjectName("subwindow_1")
Any advice? Thanks a lot. Full testing code is attached:
# Created by: PyQt5 UI code generator 5.6
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(687, 438)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.mdiArea = QtWidgets.QMdiArea(self.centralwidget)
self.mdiArea.setGeometry(QtCore.QRect(140, 10, 531, 381))
self.mdiArea.setObjectName("mdiArea")
self.subwindow = QtWidgets.QWidget()
self.subwindow.setObjectName("subwindow_test_the_object_name")
self.Add = QtWidgets.QPushButton(self.centralwidget)
self.Add.setGeometry(QtCore.QRect(10, 30, 121, 23))
self.Add.setObjectName("Add")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 687, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.Add.clicked.connect(self.Add_window) # connect the button to Add_window function
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def Add_window(self):
self.mdiArea.addSubWindow(self.subwindow)
print("there is a subwindow activated")
self.mdiArea.activeSubWindow()
self.subwindow.show()
Act_window=self.mdiArea.activeSubWindow()
print("this is subwindow 1 "+str(Act_window.objectName()))
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.subwindow.setWindowTitle(_translate("MainWindow", "Subwindow"))
self.Add.setText(_translate("MainWindow", "Add Window"))
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_())
This is a very simple sample with objectName() does not work with subwindow but it works with button and the parent MDIarea, my goal is to get the active subwindow object name such as subwindow_test_the_object_name in this case, if I have multiple subwindows with different object name, I can grab this object name as a signal. Thanks.
With the following instruction:
self.subwindow = QtWidgets.QWidget()
self.subwindow.setObjectName("subwindow_test_the_object_name")
you are giving a name to the widget that is going to be inside the QMdiSubWindow, not the QMdiSubWindow, so if you want to retrieve the name of that element you must use the widget() method of QMdiSubWindow:
def Add_window(self):
self.mdiArea.addSubWindow(self.subwindow)
print("there is a subwindow activated")
self.mdiArea.activeSubWindow()
self.subwindow.show()
Act_window =self.mdiArea.activeSubWindow()
print("this is subwindow 1 "+str(Act_window.widget().objectName()))
Output:
there is a subwindow activated
this is subwindow 1 subwindow_test_the_object_name

Categories

Resources