PyQt Can't open 3d dialog window and close the 1st one - python-3.x

In the window click Edit -> Add Row. dlg1 Dialog is executed. By default there is a data to get an error because it tries to open dlg2 Dialog. If value in the fist row is changed dlg3 Dialog will be shown.
How to i get dlg2 Dialog to show up?
How do i close dlg1 Dialog after pressing a button in it?
What am i doing wrong?
main.py
#!/usr/bin/python3
import sys
import getopt
import json, csv
import os.path
import pip
#-------------------------------------------------
from datetime import datetime, date
from dateutil.relativedelta import relativedelta
#-------------------------------------------------
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from main_window_ui import Ui_MainWindow
#-------------------------------------------------
data = [{"edrpou": "44444", "name": "Org Name 1", "serviced": ""},{"edrpou": "5666667", "name": "Org Name 2", "serviced": ""}]
fileEReports = 'data.json'
inEdrpou = ""
##################################################
def check_spaces(whatT):
w = 0
while w == 0:
whatF = input(whatT)
if (' ' in whatF):
print("error, no space allowed!")
else:
w = 1
return whatF
##################################################
def add_data_to_file(filer):
isExist = os.path.exists(filer)
if isExist == False:
with open(filer, "w+") as write_file:
#json.dump(data, write_file, sort_keys=True, indent=4, separators=(',', ': '))
json.dump(data, write_file)
write_file.close()
##################################################
def get_orgs_from_file(filer):
with open(filer, "r") as read_file:
for jsonObj in read_file:
orgsDict = json.loads(jsonObj)
read_file.close()
return orgsDict
def write_orgs_to_file(filer, data):
with open(filer, "w+") as write_file:
json.dump(data, write_file)
write_file.close()
##################################################
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self):
QMainWindow.__init__(self)
Ui_MainWindow.__init__(self)
super(MainWindow, self).__init__()
self.setupUi(self)
###################### vars ######################
self.action_add_row_orgs.triggered.connect(lambda: self.dialog_add_org())
###################### slot load ######################
def dialog_add_org(self):
dlg1 = QDialog(self)
dlg1.resize(200,30)
layout = QVBoxLayout(dlg1)
lineEdrpou = QLineEdit("5666667")
lineName = QLineEdit("Yolo")
buttonAdd = QPushButton("Add Data")
layout.addWidget(lineEdrpou)
layout.addWidget(lineName)
layout.addWidget(buttonAdd)
buttonAdd.clicked.connect(lambda: self.add_org(lineEdrpou.text(), lineName.text()))
dlg1.exec_()
# dlg1.close()
def add_org(self, edrpou, name):
new_row = [edrpou, name]
print(new_row)
add_new_organisation(fileEReports, edrpou, name, "")
# MainWindow(dialog_add_org(dlg1.close()))
def message_org_exist(self, edrpou):
dlg2 = QMessageBox(self)
dlg2.setWindowTitle("Attention!")
dlg2.setText("Organisation with Edrpou {0} already exists!".format(edrpou))
button = dlg2.exec_()
if button == QMessageBox.Ok:
print("OK!")
dlg2.close()
def add_new_organisation(filer, inEdrpou, inNewData, inType):
orgsDict = get_orgs_from_file(filer)
lenOrgsDict = len(orgsDict)
itExist = 0
for i in range(lenOrgsDict):
if orgsDict[i]["edrpou"] == inEdrpou:
itExist = itExist + 1
if itExist == 0:
dlg3 = QMessageBox()
dlg3.setWindowTitle("Success!")
dlg3.setText("Organisation {1} with Edrpou {0} was added!".format(inEdrpou, inNewData))
button2 = dlg3.exec_()
if button2 == QMessageBox.Ok:
print("OK!")
dlg3.close()
print("adding new Organisation {0} - {1}".format(inEdrpou, inNewData))
else:
MainWindow(lambda: message_org_exist(inEdrpou))
print("Organisation with this Edrpou already exist")
def main(argv):
app = QApplication(sys.argv)
window = MainWindow()
# print(PyQt5.QtWidgets.QStyleFactory.keys())
# ['Breeze', 'Oxygen', 'QtCurve', 'Windows', 'Fusion']
app.setStyle('Breeze')
window.show()
sys.exit(app.exec_())
##################################################
if __name__ == "__main__":
add_data_to_file(fileEReports)
main(sys.argv)
##################################################
main_window_ui.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui\main_window.ui'
#
# Created by: PyQt5 UI code generator 5.15.7
#
# 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_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(736, 551)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.centralwidget)
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.verticalLayoutOrgs = QtWidgets.QVBoxLayout()
self.verticalLayoutOrgs.setSpacing(3)
self.verticalLayoutOrgs.setObjectName("verticalLayoutOrgs")
self.horizontalLayoutOrgs = QtWidgets.QHBoxLayout()
self.horizontalLayoutOrgs.setSizeConstraint(QtWidgets.QLayout.SetDefaultConstraint)
self.horizontalLayoutOrgs.setSpacing(3)
self.horizontalLayoutOrgs.setObjectName("horizontalLayoutOrgs")
self.checkBoxServiced = QtWidgets.QCheckBox(self.centralwidget)
self.checkBoxServiced.setLocale(QtCore.QLocale(QtCore.QLocale.Ukrainian, QtCore.QLocale.Ukraine))
self.checkBoxServiced.setChecked(True)
self.checkBoxServiced.setObjectName("checkBoxServiced")
self.horizontalLayoutOrgs.addWidget(self.checkBoxServiced)
self.checkBoxUr = QtWidgets.QCheckBox(self.centralwidget)
self.checkBoxUr.setChecked(True)
self.checkBoxUr.setObjectName("checkBoxUr")
self.horizontalLayoutOrgs.addWidget(self.checkBoxUr)
self.checkBoxFop = QtWidgets.QCheckBox(self.centralwidget)
self.checkBoxFop.setChecked(True)
self.checkBoxFop.setObjectName("checkBoxFop")
self.horizontalLayoutOrgs.addWidget(self.checkBoxFop)
self.horizontalLayoutOrgs.setStretch(2, 1)
self.verticalLayoutOrgs.addLayout(self.horizontalLayoutOrgs)
spacerItem = QtWidgets.QSpacerItem(0, 8, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
self.verticalLayoutOrgs.addItem(spacerItem)
self.lineEditOrgs = QtWidgets.QLineEdit(self.centralwidget)
self.lineEditOrgs.setObjectName("lineEditOrgs")
self.verticalLayoutOrgs.addWidget(self.lineEditOrgs)
self.tableViewOrgs = QtWidgets.QTableView(self.centralwidget)
self.tableViewOrgs.setLocale(QtCore.QLocale(QtCore.QLocale.Ukrainian, QtCore.QLocale.Ukraine))
self.tableViewOrgs.setAlternatingRowColors(True)
self.tableViewOrgs.setObjectName("tableViewOrgs")
self.verticalLayoutOrgs.addWidget(self.tableViewOrgs)
self.horizontalLayout.addLayout(self.verticalLayoutOrgs)
self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
self.tabWidget.setObjectName("tabWidget")
self.tab_keys = QtWidgets.QWidget()
self.tab_keys.setObjectName("tab_keys")
self.verticalLayoutKeys = QtWidgets.QVBoxLayout(self.tab_keys)
self.verticalLayoutKeys.setContentsMargins(0, 3, 0, 0)
self.verticalLayoutKeys.setSpacing(3)
self.verticalLayoutKeys.setObjectName("verticalLayoutKeys")
self.lineEditKeys = QtWidgets.QLineEdit(self.tab_keys)
self.lineEditKeys.setObjectName("lineEditKeys")
self.verticalLayoutKeys.addWidget(self.lineEditKeys)
self.tableViewKeys = QtWidgets.QTableView(self.tab_keys)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.tableViewKeys.sizePolicy().hasHeightForWidth())
self.tableViewKeys.setSizePolicy(sizePolicy)
self.tableViewKeys.setLocale(QtCore.QLocale(QtCore.QLocale.Ukrainian, QtCore.QLocale.Ukraine))
self.tableViewKeys.setObjectName("tableViewKeys")
self.verticalLayoutKeys.addWidget(self.tableViewKeys)
self.tabWidget.addTab(self.tab_keys, "")
self.tab_lic = QtWidgets.QWidget()
self.tab_lic.setObjectName("tab_lic")
self.verticalLayoutLic = QtWidgets.QVBoxLayout(self.tab_lic)
self.verticalLayoutLic.setContentsMargins(0, 3, 0, 0)
self.verticalLayoutLic.setSpacing(3)
self.verticalLayoutLic.setObjectName("verticalLayoutLic")
self.lineEditLic = QtWidgets.QLineEdit(self.tab_lic)
self.lineEditLic.setObjectName("lineEditLic")
self.verticalLayoutLic.addWidget(self.lineEditLic)
self.tableViewLic = QtWidgets.QTableView(self.tab_lic)
self.tableViewLic.setLocale(QtCore.QLocale(QtCore.QLocale.Ukrainian, QtCore.QLocale.Ukraine))
self.tableViewLic.setObjectName("tableViewLic")
self.verticalLayoutLic.addWidget(self.tableViewLic)
self.tabWidget.addTab(self.tab_lic, "")
self.tab_acc = QtWidgets.QWidget()
self.tab_acc.setObjectName("tab_acc")
self.verticalLayoutAcc = QtWidgets.QVBoxLayout(self.tab_acc)
self.verticalLayoutAcc.setContentsMargins(0, 3, 0, 0)
self.verticalLayoutAcc.setSpacing(3)
self.verticalLayoutAcc.setObjectName("verticalLayoutAcc")
self.lineEditAcc = QtWidgets.QLineEdit(self.tab_acc)
self.lineEditAcc.setObjectName("lineEditAcc")
self.verticalLayoutAcc.addWidget(self.lineEditAcc)
self.tableViewAcc = QtWidgets.QTableView(self.tab_acc)
self.tableViewAcc.setLocale(QtCore.QLocale(QtCore.QLocale.Ukrainian, QtCore.QLocale.Ukraine))
self.tableViewAcc.setObjectName("tableViewAcc")
self.verticalLayoutAcc.addWidget(self.tableViewAcc)
self.tabWidget.addTab(self.tab_acc, "")
self.horizontalLayout.addWidget(self.tabWidget)
self.horizontalLayout.setStretch(0, 2)
self.horizontalLayout.setStretch(1, 4)
self.horizontalLayout_2.addLayout(self.horizontalLayout)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 736, 21))
self.menubar.setObjectName("menubar")
self.menuFile = QtWidgets.QMenu(self.menubar)
self.menuFile.setObjectName("menuFile")
self.menu_Edit = QtWidgets.QMenu(self.menubar)
self.menu_Edit.setObjectName("menu_Edit")
self.menu_Option = QtWidgets.QMenu(self.menubar)
self.menu_Option.setObjectName("menu_Option")
MainWindow.setMenuBar(self.menubar)
self.toolBar = QtWidgets.QToolBar(MainWindow)
self.toolBar.setObjectName("toolBar")
MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.action_open = QtWidgets.QAction(MainWindow)
self.action_open.setObjectName("action_open")
self.action_open_recent = QtWidgets.QAction(MainWindow)
self.action_open_recent.setObjectName("action_open_recent")
self.action_save = QtWidgets.QAction(MainWindow)
self.action_save.setObjectName("action_save")
self.action_exit = QtWidgets.QAction(MainWindow)
self.action_exit.setObjectName("action_exit")
self.action_pref = QtWidgets.QAction(MainWindow)
self.action_pref.setObjectName("action_pref")
self.action_org_name = QtWidgets.QAction(MainWindow)
self.action_org_name.setObjectName("action_org_name")
self.action_key = QtWidgets.QAction(MainWindow)
self.action_key.setObjectName("action_key")
self.action_copy_edrpou = QtWidgets.QAction(MainWindow)
self.action_copy_edrpou.setObjectName("action_copy_edrpou")
self.action_copy_name = QtWidgets.QAction(MainWindow)
self.action_copy_name.setObjectName("action_copy_name")
self.action_copy_pass_dir = QtWidgets.QAction(MainWindow)
self.action_copy_pass_dir.setObjectName("action_copy_pass_dir")
self.action_copy_pass_stamp = QtWidgets.QAction(MainWindow)
self.action_copy_pass_stamp.setObjectName("action_copy_pass_stamp")
self.action_copy_pass_acc = QtWidgets.QAction(MainWindow)
self.action_copy_pass_acc.setObjectName("action_copy_pass_acc")
self.action_copy_active_line_pass = QtWidgets.QAction(MainWindow)
self.action_copy_active_line_pass.setObjectName("action_copy_active_line_pass")
self.action_add_row_orgs = QtWidgets.QAction(MainWindow)
self.action_add_row_orgs.setObjectName("action_add_row_orgs")
self.action_remove_row_orgs = QtWidgets.QAction(MainWindow)
self.action_remove_row_orgs.setObjectName("action_remove_row_orgs")
self.menuFile.addAction(self.action_open)
self.menuFile.addAction(self.action_open_recent)
self.menuFile.addSeparator()
self.menuFile.addAction(self.action_save)
self.menuFile.addSeparator()
self.menuFile.addAction(self.action_exit)
self.menuFile.addSeparator()
self.menu_Edit.addAction(self.action_add_row_orgs)
self.menu_Edit.addAction(self.action_remove_row_orgs)
self.menu_Edit.addSeparator()
self.menu_Edit.addAction(self.action_org_name)
self.menu_Edit.addAction(self.action_key)
self.menu_Edit.addSeparator()
self.menu_Edit.addAction(self.action_copy_edrpou)
self.menu_Edit.addAction(self.action_copy_name)
self.menu_Edit.addAction(self.action_copy_pass_dir)
self.menu_Edit.addAction(self.action_copy_pass_stamp)
self.menu_Edit.addAction(self.action_copy_pass_acc)
self.menu_Edit.addSeparator()
self.menu_Edit.addAction(self.action_copy_active_line_pass)
self.menu_Option.addAction(self.action_pref)
self.menubar.addAction(self.menuFile.menuAction())
self.menubar.addAction(self.menu_Edit.menuAction())
self.menubar.addAction(self.menu_Option.menuAction())
self.toolBar.addAction(self.action_open)
self.toolBar.addAction(self.action_save)
self.toolBar.addSeparator()
self.toolBar.addAction(self.action_copy_edrpou)
self.toolBar.addAction(self.action_copy_name)
self.toolBar.addAction(self.action_copy_pass_dir)
self.toolBar.addAction(self.action_copy_pass_stamp)
self.toolBar.addAction(self.action_copy_pass_acc)
self.retranslateUi(MainWindow)
self.tabWidget.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
MainWindow.setTabOrder(self.checkBoxServiced, self.checkBoxUr)
MainWindow.setTabOrder(self.checkBoxUr, self.checkBoxFop)
MainWindow.setTabOrder(self.checkBoxFop, self.lineEditOrgs)
MainWindow.setTabOrder(self.lineEditOrgs, self.tabWidget)
MainWindow.setTabOrder(self.tabWidget, self.lineEditKeys)
MainWindow.setTabOrder(self.lineEditKeys, self.lineEditLic)
MainWindow.setTabOrder(self.lineEditLic, self.tableViewLic)
MainWindow.setTabOrder(self.tableViewLic, self.lineEditAcc)
MainWindow.setTabOrder(self.lineEditAcc, self.tableViewAcc)
MainWindow.setTabOrder(self.tableViewAcc, self.tableViewOrgs)
MainWindow.setTabOrder(self.tableViewOrgs, self.tableViewKeys)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.centralwidget.setWhatsThis(_translate("MainWindow", "<html><head/><body><p><br/></p></body></html>"))
self.checkBoxServiced.setText(_translate("MainWindow", "Serviced"))
self.checkBoxUr.setText(_translate("MainWindow", "Show Ur"))
self.checkBoxFop.setText(_translate("MainWindow", "Show Fop"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_keys), _translate("MainWindow", "Keys"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_lic), _translate("MainWindow", "Licenses"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_acc), _translate("MainWindow", "Accountants"))
self.menuFile.setTitle(_translate("MainWindow", "&File"))
self.menu_Edit.setTitle(_translate("MainWindow", "&Edit"))
self.menu_Option.setTitle(_translate("MainWindow", "&Option"))
self.toolBar.setWindowTitle(_translate("MainWindow", "toolBar"))
self.action_open.setText(_translate("MainWindow", "&Open"))
self.action_open.setToolTip(_translate("MainWindow", "Open file"))
self.action_open_recent.setText(_translate("MainWindow", "Open recent"))
self.action_open_recent.setToolTip(_translate("MainWindow", "Open recent file"))
self.action_save.setText(_translate("MainWindow", "&Save"))
self.action_save.setToolTip(_translate("MainWindow", "Save file"))
self.action_exit.setText(_translate("MainWindow", "E&xit"))
self.action_pref.setText(_translate("MainWindow", "Preferences"))
self.action_org_name.setText(_translate("MainWindow", "Name and Edrpou"))
self.action_key.setText(_translate("MainWindow", "Key"))
self.action_key.setToolTip(_translate("MainWindow", "Changing Key Data"))
self.action_copy_edrpou.setText(_translate("MainWindow", "Copy Edrpou"))
self.action_copy_name.setText(_translate("MainWindow", "Copy Name"))
self.action_copy_pass_dir.setText(_translate("MainWindow", "Copy Password Dir"))
self.action_copy_pass_stamp.setText(_translate("MainWindow", "Copy Password Stamp"))
self.action_copy_pass_acc.setText(_translate("MainWindow", "Copy Password Accountant"))
self.action_copy_active_line_pass.setText(_translate("MainWindow", "Copy Pass"))
self.action_add_row_orgs.setText(_translate("MainWindow", "Add Row"))
self.action_remove_row_orgs.setText(_translate("MainWindow", "Remove Row"))
======================== edit ========================
I've found a solution to one of my problems. Now the first dialog is closing after second diaog button pressed.
Added this connect signal before dlg1.exec_():
buttonAdd.clicked.connect(dlg1.close_clicked)
dlg1.exec_()
And a small class:
class Dialog(QDialog):
def __init__(self):
QDialog.__init__(self)
def close_clicked(self):
self.close()
And used it
dlg1 = Dialog()
======================== edit 2 ========================
And i've found solution to my other trouble here:
https://www.w3docs.com/snippets/python/typeerror-missing-1-required-positional-argument-self.html
# MainWindow.message_org_exist(inEdrpou)
my_instance = MainWindow()
my_instance.message_org_exist(inEdrpou) # This works

Related

How to let pyqt update the ui in the thread without blocking the interface?

I am trying to apply the load icon to the button, but I find that when I process time-consuming operations, it will cause a deadlock. I don't want to execute time. sleep (), which will affect the efficiency of the program. How should I optimize this code.
This is the original project:
https://github.com/prasanna892/PyQt5_loading_screen
To reduce wastage, I removed some code
loding_Screen.py
import os, inspect, sys
from PyQt5.QtWidgets import QWidget, QLabel, QGridLayout, QGraphicsOpacityEffect
from PyQt5.QtCore import QSize, Qt, QThread, QTimer
from PyQt5.QtGui import QMovie, QPalette, QColor
class LoadingTranslucentScreen(QWidget):
def __init__(self, parent: QWidget, description_text: str = '', dot_animation: bool = False):
super().__init__(parent)
self.__parent = parent
self.__parent.installEventFilter(self)
self.__parent.resizeEvent = self.resizeEvent
self.__dot_animation_flag = dot_animation
self.__descriptionLbl_original_text = description_text
self.__initUi(description_text)
def __initUi(self, description_text):
self.setAttribute(Qt.WA_TransparentForMouseEvents, True)
self.__movieLbl = QLabel(self.__parent)
caller_path = os.path.dirname(inspect.getframeinfo(sys._getframe(1)).filename)
loading_screen_ico_filename = os.path.join(caller_path, 'ico/Loading.gif')
self.__loading_mv = QMovie(loading_screen_ico_filename)
self.__loading_mv.setScaledSize(QSize(25, 25))
self.__movieLbl.setMovie(self.__loading_mv)
# self.__movieLbl.setStyleSheet('QLabel { background: transparent; }')
self.__movieLbl.setAlignment(Qt.AlignVCenter | Qt.AlignCenter)
self.__descriptionLbl = QLabel()
if description_text.strip() != '':
self.__descriptionLbl.setText(description_text)
self.__descriptionLbl.setVisible(False)
self.__descriptionLbl.setAlignment(Qt.AlignVCenter | Qt.AlignCenter)
lay = QGridLayout()
lay.setContentsMargins(0, 0, 0, 0)
lay.setAlignment(Qt.AlignVCenter | Qt.AlignCenter)
self.setLayout(lay)
self.setDescriptionLabelDirection('Bottom') # default description label direction
self.setMinimumSize(self.__parent.width(), self.__parent.height())
self.setVisible(False)
# self.__timerInit()
# def __timerInit(self):
# if self.__dot_animation_flag:
# self.__timer = QTimer(self)
# self.__timer.timeout.connect(self.__ticking)
# self.__timer.singleShot(0, self.__ticking)
# self.__timer.start(500)
#
# def __ticking(self):
# dot = '.'
# cur_text = self.__descriptionLbl.text()
# cnt = cur_text.count(dot)
# if cnt % 3 == 0 and cnt != 0:
# self.__descriptionLbl.setText(self.__descriptionLbl_original_text + dot)
# else:
# self.__descriptionLbl.setText(cur_text + dot)
def setParentThread(self, parent_thread: QThread):
self.__thread = parent_thread
def setDescriptionLabelDirection(self, direction: str):
lay = self.layout()
if direction == 'Left':
lay.addWidget(self.__descriptionLbl, 0, 0, 1, 1)
lay.addWidget(self.__movieLbl, 0, 1, 1, 1)
elif direction == 'Top':
lay.addWidget(self.__descriptionLbl, 0, 0, 1, 1)
lay.addWidget(self.__movieLbl, 1, 0, 1, 1)
elif direction == 'Right':
lay.addWidget(self.__movieLbl, 0, 0, 1, 1)
lay.addWidget(self.__descriptionLbl, 0, 1, 1, 1)
elif direction == 'Bottom':
lay.addWidget(self.__movieLbl, 0, 0, 1, 1)
lay.addWidget(self.__descriptionLbl, 1, 0, 1, 1)
else:
raise BaseException('Invalid direction.')
def start(self):
self.__loading_mv.start()
self.__descriptionLbl.setVisible(True)
self.raise_()
self.setVisible(True)
# opacity_effect = QGraphicsOpacityEffect(opacity=0.75)
# self.setGraphicsEffect(opacity_effect)
def stop(self):
self.__loading_mv.stop()
self.__descriptionLbl.setVisible(False)
self.lower()
self.setVisible(False)
def makeParentDisabledDuringLoading(self):
if self.__thread.isRunning():
self.__parent.setEnabled(False)
else:
self.__parent.setEnabled(True)
def paintEvent(self, e):
palette = QPalette()
palette.setColor(QPalette.Window, QColor(255, 255, 255))
self.setAutoFillBackground(True)
self.setPalette(palette)
return super().paintEvent(e)
def eventFilter(self, obj, e):
if isinstance(obj, QWidget):
if e.type() == 14:
self.setFixedSize(e.size())
return super(LoadingTranslucentScreen, self).eventFilter(obj, e)
To facilitate understanding, this is a small example I wrote:
main.py
`
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtCore import QWaitCondition, QMutex
from PyQt5.QtWidgets import QMainWindow, QMessageBox, QApplication, QDesktopWidget
from PyQt5.QtCore import pyqtSignal
import sys
from PyQt5.QtCore import QThread
from pyqt_translucent_full_loading_screen_thread import LoadingThread, LoadingTranslucentScreen
class MySearch_Loading_Thread(LoadingThread):
loadingSignal = pyqtSignal()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.cond = QWaitCondition()
self.mutex = QMutex()
def resume(self):
self.cond.wakeAll()
def run(self):
self.mutex.lock()
self.cond.wait(self.mutex)
self.mutex.unlock()
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.horizontalLayout = QtWidgets.QHBoxLayout(self.centralwidget)
self.horizontalLayout.setObjectName("horizontalLayout")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setObjectName("pushButton")
self.horizontalLayout.addWidget(self.pushButton)
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setObjectName("label")
self.horizontalLayout.addWidget(self.label)
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_2.setObjectName("pushButton_2")
self.horizontalLayout.addWidget(self.pushButton_2)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 23))
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.label.setText(_translate("MainWindow", "TextLabel"))
self.pushButton_2.setText(_translate("MainWindow", "stop"))
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.__init2__()
def __init2__(self):
self.search_running = False
self.ui.pushButton.clicked.connect(self.search)
self.ui.pushButton_2.clicked.connect(self.stop_search)
def stop_search(self):
if self.search_running:
reply = QMessageBox.information(self, 'notice', 'Do you want to stop searching?',
QMessageBox.Yes | QMessageBox.Cancel)
if reply == QMessageBox.Yes:
self.search_thread.terminate()
self.__thread.resume()
self.search_running = False
else:
QMessageBox.information(self, 'tip', 'no search!', QMessageBox.Ok)
def search(self):
if not self.search_running:
self.__loadingTranslucentScreen = LoadingTranslucentScreen(parent=self.ui.pushButton,
description_text='搜索中')
self.__loadingTranslucentScreen.setDescriptionLabelDirection('Right')
self.__thread = MySearch_Loading_Thread(loading_screen=self.__loadingTranslucentScreen)
self.__thread.start()
self.search_running = True
self.search_thread = Search_Thread()
self.search_thread.trigger.connect(lambda i: self.ui.label.setText(str(i)))
self.search_thread.complete.connect(self.search_complete)
self.search_thread.start()
def search_complete(self):
self.__thread.resume()
self.search_running = False
class Search_Thread(QThread):
trigger = pyqtSignal(int)
complete = pyqtSignal()
def __init__(self):
super().__init__()
def run(self):
for i in range(10000):
for j in range(10000):
for k in range(10000):
# time.sleep(0.1)
self.trigger.emit(i + j + k)
self.complete.emit()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
screen = QDesktopWidget().screenGeometry()
height = 100
width = 300
window.setGeometry(int((screen.width() - width) / 2), int((screen.height() - height) / 2), width, height)
window.setWindowTitle("test")
window.show()
sys.exit(app.exec())
`

Pass dictionary of lists to Qtablewidget - PyQT5

I have used PyQT5 to create the UI of a search engine. I have been able to let the application open a folder containing a pdf file, create an index file, search within it and export the results as txt and excel file. Running the code attached will do it.
I wanted to give the user also an immediate view of the results via Qtablewidget. The results of the search are store as dictionary to self.data.
Below is represented how the widget read the variable for a specific example.
Has you can see the widget read the number of column and rows of the variable but does not fill the cells.
The error I have experienced related to the fact that I queried the self.data as if it was a list lists rather than a dictionary of lists.
This is the code that is complete code.
from PyQt5 import QtCore, QtGui, QtWidgets, QtWidgets
from PyQt5.QtWidgets import QHeaderView, QTableWidgetItem
import os, os.path
import glob
import os
from PyPDF2 import PdfFileReader, PdfFileWriter
import pdftotext
from whoosh import index
from whoosh.fields import Schema, TEXT, ID, STORED
from whoosh.analysis import RegexTokenizer
from whoosh.analysis import StopFilter
from whoosh import scoring
from whoosh.index import open_dir
from whoosh import qparser
from whoosh import highlight
import pandas as pd
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1126, 879)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(40, 30, 100, 30))
self.pushButton.setObjectName("pushButton")
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(180, 30, 120, 30))
self.pushButton_2.setObjectName("pushButton_2")
self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_3.setGeometry(QtCore.QRect(620, 30, 80, 30))
self.pushButton_3.setObjectName("pushButton_3")
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(380, 60, 191, 21))
self.lineEdit.setObjectName("lineEdit")
self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit_2.setGeometry(QtCore.QRect(40, 90, 50, 21))
self.lineEdit_2.setObjectName("lineEdit_2")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(380, 30, 50, 35))
font = QtGui.QFont()
font.setPointSize(10)
self.label.setFont(font)
self.label.setObjectName("label")
self.label2 = QtWidgets.QLabel(self.centralwidget)
self.label2.setGeometry(QtCore.QRect(40, 70, 150, 16))
font = QtGui.QFont()
font.setPointSize(10)
self.label2.setFont(font)
self.label2.setObjectName("label")
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget.setGeometry(QtCore.QRect(0, 120, 1121, 721))
self.tableWidget.setObjectName("tableWidget")
#self.tableWidget.setColumnCount(2)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1126, 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)
self.pushButton.clicked.connect(self.open_directory)
self.pushButton_2.clicked.connect(self.createindex)
self.pushButton_3.clicked.connect(self.export)
self.lineEdit.returnPressed.connect(self.search)
self.lineEdit.returnPressed.connect(self.datatable)
def datatable(self):
data = self.data
numrows = len(self.data)
numcols = len(self.data[0])
self.tableWidget.setColumnCount(numcols)
self.tableWidget.setRowCount(numrows)
for row in range(numrows):
for column in range(numcols):
self.tableWidget.setItem(row, column, QTableWidgetItem((self.data[row][column])))
def open_directory(self):
self.dialog = QtWidgets.QFileDialog()
self.folder_path = self.dialog.getExistingDirectory(None, "Select Folder")
return self.folder_path
def createindex(self):
os.chdir(self.folder_path)
self.mypdfiles = glob.glob("*.pdf")
#creation of folder for splitted files
MYDIR = ("Splitted")
CHECK_FOLDER = os.path.isdir(MYDIR)
if not CHECK_FOLDER:
os.makedirs(MYDIR)
# save split downloaded file and save into new folder
for self.file in self.mypdfiles:
self.fname = os.path.splitext(os.path.basename(self.file))[0]
self.pdf = PdfFileReader(self.file)
for self.page in range(self.pdf.getNumPages()):
self.pdfwrite = PdfFileWriter()
self.pdfwrite.addPage(self.pdf.getPage(self.page))
self.outputfilename = '{}_page_{}.pdf'.format(self.fname, self.page+1)
with open(os.path.join("./Splitted", self.outputfilename), 'wb') as out:
self.pdfwrite.write(out)
print('Created: {}'.format(self.outputfilename))
#set working directory
os.chdir(self.folder_path + "/Splitted")
self.spltittedfiles = glob.glob("*.pdf")
MYDIR = ("Txt")
CHECK_FOLDER = os.path.isdir(MYDIR)
if not CHECK_FOLDER:
os.makedirs(MYDIR)
# Load your PDF
for self.file in self.spltittedfiles:
with open(self.file, "rb") as f:
self.pdf = pdftotext.PDF(f)
#creation of folder for splitted files
# Save all text to a txt file.
with open(os.path.join("./TXT", os.path.splitext(os.path.basename(self.file))[0] + ".txt") , 'w', encoding = 'utf-8') as f:
f.write("\n\n".join(self.pdf))
f.close()
os.chdir(self.folder_path)
MYDIR = ("indexdir")
CHECK_FOLDER = os.path.isdir(MYDIR)
if not CHECK_FOLDER:
os.makedirs(MYDIR)
self.my_analyzer = RegexTokenizer()| StopFilter(lang = "en")
self.schema = Schema(title=TEXT(stored=True),path=ID(stored=True),
content=TEXT(analyzer = self.my_analyzer),
textdata=TEXT(stored=True))
# set an index writer to add document as per schema
self.ix = index.create_in("indexdir",self.schema)
self.writer = self.ix.writer()
self.filepaths = [os.path.join("./Splitted/Txt",i) for i in os.listdir("./Splitted/Txt")]
for path in self.filepaths:
self.fp = open(path, "r", encoding='utf-8')
self.text = self.fp.read()
self.writer.add_document(title = os.path.splitext(os.path.basename(path))[0] , path=path, content=self.text,textdata=self.text)
self.fp.close()
self.writer.commit()
def search(self):
os.chdir(self.folder_path)
self.ix = open_dir("indexdir")
MYDIR = ("Results")
CHECK_FOLDER = os.path.isdir(MYDIR)
if not CHECK_FOLDER:
os.makedirs(MYDIR)
self.text = self.lineEdit.text()
self.query_str = self.text
self.query = qparser.QueryParser("textdata", schema = self.ix.schema)
self.q = self.query.parse(self.query_str)
self.topN = self.lineEdit_2.text()
if self.lineEdit_2.text() == "":
self.topN = 1000
else:
self.topN = int(self.lineEdit_2.text())
self.data=[]
with self.ix.searcher() as searcher:
self.results = searcher.search(self.q, terms=True, limit=self.topN)
Upper = highlight.UppercaseFormatter()
self.results.formatter = Upper
my_cf = highlight.ContextFragmenter(maxchars=500, surround=300)
self.results.fragmenter = my_cf
for self.i in self.results:
self.data.append({"title": self.i['title'], "text": self.i.highlights('textdata'), "score": str(self.i.score)})
pd.DataFrame(self.data).to_excel("data.xlsx")
def export(self):
with self.ix.searcher() as searcher:
self.results = searcher.search(self.q, terms=True, limit= None)
Upper = highlight.UppercaseFormatter()
self.results.formatter = Upper
my_cf = highlight.ContextFragmenter(maxchars=500, surround=300)
self.results.fragmenter = my_cf
self.countrow = len(self.results)
for self.i in self.results:
with open(os.path.join(self.folder_path, self.text + ".txt"), 'a', encoding="utf-8") as f:
print("Title {}".format(self.i['title']), "Text {}".format(self.i.highlights('textdata')), file=f)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Search Text"))
self.pushButton.setText(_translate("MainWindow", "Select Folder"))
self.pushButton_2.setText(_translate("MainWindow", "Create Database"))
self.pushButton_3.setText(_translate("MainWindow", "Export"))
self.label.setText(_translate("MainWindow", "Search"))
self.label2.setText(_translate("MainWindow", "Top Results"))
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 was dealing with a list of dictionaries that I needed to unnest.
I have slightly modified the datatable function:
def datatable(self):
data = self.data
numrows = len(self.data)
numcols = len(self.data[0])
self.tableWidget.setColumnCount(numcols)
self.tableWidget.setRowCount(numrows)
self.tableWidget.setHorizontalHeaderLabels((list(self.data[0].keys())))
for row in range(numrows):
for column in range(numcols):
item = (list(self.data[row].values())[column])
self.tableWidget.setItem(row, column, QTableWidgetItem(item))

Pyqt5 QFileDialog not working in my program for Getting Directories

I have This Qt MainWindow Shown Below:
I want my Browse button to Open a Dialog box for selecting Specific Directory.
I Went through the various post on Stack Overflow, I tried implementing the solution in the post, but It's not working for me.
Here is my Code :
from PyQt5 import QtCore, QtGui, QtWidgets
import os
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.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName("gridLayout")
self.gridLayout_2 = QtWidgets.QGridLayout()
self.gridLayout_2.setObjectName("gridLayout_2")
self.start_button = QtWidgets.QPushButton(self.centralwidget)
self.start_button.setAutoFillBackground(False)
self.start_button.setAutoDefault(False)
self.start_button.setDefault(False)
self.start_button.setFlat(False)
self.start_button.setObjectName("start_button")
self.start_button.clicked.connect(lambda: self.start_button_click())
self.gridLayout_2.addWidget(self.start_button, 0, 0, 1, 1)
self.Br_button = QtWidgets.QPushButton(self.centralwidget)
self.Br_button.setObjectName("Br_button")
self.Br_button.clicked.connect(lambda: self.browse_button())
self.gridLayout_2.addWidget(self.Br_button, 2, 0, 1, 1)
self.label = QtWidgets.QLabel(self.centralwidget)
font = QtGui.QFont()
font.setPointSize(14)
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setObjectName("label")
self.gridLayout_2.addWidget(self.label, 2, 1, 1, 1, QtCore.Qt.AlignHCenter)
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(0)
self.tableWidget.setRowCount(0)
self.gridLayout_2.addWidget(self.tableWidget, 3, 0, 1, 2)
self.gridLayout.addLayout(self.gridLayout_2, 0, 0, 1, 1)
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.start_button.setToolTip(_translate("MainWindow", "Start The Program"))
self.start_button.setText(_translate("MainWindow", "Start"))
self.Br_button.setToolTip(_translate("MainWindow", "Browse the File Location to Watch on"))
self.Br_button.setText(_translate("MainWindow", "Browse"))
def start_button_click(self):
self.label.setText("Hello")
def browse_button(self):
fileName = QtWidgets.QFileDialog.getExistingDirectory(QtWidgets.QFileDialog,None,"Open Directory",os.getcwd(), QtWidgets.QFileDialog.ShowDirsOnly)
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_())
When I Click on the Browse button it closes the Application abruptly after few seconds and I am Getting This Error Shown below:
Try it:
import sys
import os
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class Form(QMainWindow):
def __init__(self,parent=None):
super().__init__(parent)
self.plainTextEdit = QPlainTextEdit()
self.plainTextEdit.setFont(QFont('Arial', 11))
openDirButton = QPushButton("Open Directory")
openDirButton.clicked.connect(self.browse_button)
layoutV = QVBoxLayout()
layoutV.addWidget(openDirButton)
layoutH = QHBoxLayout()
layoutH.addLayout(layoutV)
layoutH.addWidget(self.plainTextEdit)
centerWidget = QWidget()
centerWidget.setLayout(layoutH)
self.setCentralWidget(centerWidget)
def browse_button(self):
fileName = QFileDialog.getExistingDirectory(
#QtWidgets.QFileDialog, # ???
None,
"Open Directory",
os.getcwd(),
QFileDialog.ShowDirsOnly)
self.plainTextEdit.appendHtml("<br>Chose a folder: <b>{}</b>".format(fileName))
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Form()
ex.resize(740,480)
ex.setWindowTitle("PyQt5-QFileDialog")
ex.show()
sys.exit(app.exec_())

Python - showing next Tab by pressing a button

How can I change the Tab beeing shown by pressing an button ?
The function is beeing called by pressing a button in a message box.
I have tried setCurrentIndex() but the Tab beeing shown will not change.
I am using Python 3.6 and pyqt5.
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))
self.tabWidget.setLayoutDirection(QtCore.Qt.LeftToRight)
self.tabWidget.setTabPosition(QtWidgets.QTabWidget.West)
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.tab_v3 = QtWidgets.QWidget()
self.addTab(self.tab_v3, "Tab 3")
self.openFile = QPushButton("Choose Tab ", self.tab_v1)
self.openFile.setGeometry(QtCore.QRect(700, 25, 200, 30))
self.openFile.clicked.connect(self.on_click_do)
def on_click_do(self):
box1 = QMessageBox()
box1.setIcon(QMessageBox.Question)
box1.setWindowTitle('Information')
box1.setText(
"Do you want to go to the next Tab?")
box1.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
buttonY = box1.button(QMessageBox.Yes)
buttonY.setText('Yes') ##translation
buttonN = box1.button(QMessageBox.No)
buttonN.setText('No') ## translation
box1.exec_()
if box1.clickedButton() == buttonN:
pass
elif box1.clickedButton() == buttonY:
self.tabWidget.setCurrentIndex(1)
def main():
app = QApplication(sys.argv)
ex = main_window()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Try it:
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))
self.tabWidget.setLayoutDirection(QtCore.Qt.LeftToRight)
self.tabWidget.setTabPosition(QtWidgets.QTabWidget.West)
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.tab_v3 = QtWidgets.QWidget()
self.addTab(self.tab_v3, "Tab 3")
self.openFile = QPushButton("Choose Tab ", self.tab_v1)
self.openFile.setGeometry(QtCore.QRect(700, 25, 200, 30))
self.openFile.clicked.connect(self.on_click_do)
def on_click_do(self):
box1 = QMessageBox()
box1.setIcon(QMessageBox.Question)
box1.setWindowTitle('Information')
box1.setText(
"Do you want to go to the next Tab?")
box1.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
buttonY = box1.button(QMessageBox.Yes)
buttonY.setText('Yes') ##translation
buttonN = box1.button(QMessageBox.No)
buttonN.setText('No') ## translation
box1.exec_()
if box1.clickedButton() == buttonN:
pass
elif box1.clickedButton() == buttonY:
#self.tabWidget.setCurrentIndex(1) # ---
self.setCurrentIndex(1) # +++
def main():
app = QApplication(sys.argv)
ex = main_window()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()

how to use python script in pyqt5 ui widget code

I am having a pyhton script having some code as follows and and .ui file converted into the .py file. Now i want to execute the python script in widget code of gui widget?
Please help me how can i do that .
from PyQt5 import QtCore, QtGui, QtWidgets
import DC_gimbal as backend
import hudsup as hp
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(978, 600)
self.hudsup = hudsup()
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(0, 0, 291, 261))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.Heads_up = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.Heads_up.setContentsMargins(0, 0, 0, 0)
self.Heads_up.setObjectName("Heads_up")
self.widget = QtWidgets.QWidget(self.verticalLayoutWidget)
self.widget.setObjectName("widget")
self.HeadsWidget = QtWidgets.QWidget(self.widget)
self.HeadsWidget.setGeometry(QtCore.QRect(0, 0, 291, 261))
self.HeadsWidget.setObjectName("HeadsWidget")
self.Heads_up.addWidget(self.widget)
self.Heads_up.addWidget(self.huds_Up())
self.verticalLayoutWidget_2 = QtWidgets.QWidget(self.centralwidget)
self.verticalLayoutWidget_2.setGeometry(QtCore.QRect(0, 260, 291, 291))
self.verticalLayoutWidget_2.setObjectName("verticalLayoutWidget_2")
self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget_2)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setObjectName("verticalLayout")
self.widget_3 = QtWidgets.QWidget(self.verticalLayoutWidget_2)
self.widget_3.setObjectName("widget_3")
self.displayWidget = QtWidgets.QWidget(self.widget_3)
self.displayWidget.setGeometry(QtCore.QRect(0, 0, 291, 281))
self.displayWidget.setObjectName("displayWidget")
self.verticalLayout.addWidget(self.widget_3)
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(500, 10, 93, 28))
self.pushButton.setObjectName("connect")
self.pushButton.clicked.connect(backend.Noctua_initialise())
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(620, 10, 93, 28))
self.pushButton_2.setObjectName("pushButton_2")
self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_3.setGeometry(QtCore.QRect(740, 10, 93, 28))
self.pushButton_3.setObjectName("pushButton_3")
self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
self.tabWidget.setGeometry(QtCore.QRect(290, 330, 561, 211))
self.tabWidget.setObjectName("tabWidget")
self.tab = QtWidgets.QWidget()
self.tab.setObjectName("tab")
self.tabWidget.addTab(self.tab, "")
self.tab_2 = QtWidgets.QWidget()
self.tab_2.setObjectName("tab_2")
self.tabWidget.addTab(self.tab_2, "")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 978, 26))
self.menubar.setObjectName("menubar")
self.menuconnect = QtWidgets.QMenu(self.menubar)
self.menuconnect.setObjectName("menuconnect")
self.menuDisconnect = QtWidgets.QMenu(self.menubar)
self.menuDisconnect.setObjectName("menuDisconnect")
self.menuMode = QtWidgets.QMenu(self.menubar)
self.menuMode.setObjectName("menuMode")
self.menuSensors = QtWidgets.QMenu(self.menubar)
self.menuSensors.setObjectName("menuSensors")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.actionLIDAR = QtWidgets.QAction(MainWindow)
self.actionLIDAR.setObjectName("actionLIDAR")
self.actionOpen_CV = QtWidgets.QAction(MainWindow)
self.actionOpen_CV.setObjectName("actionOpen_CV")
self.actionManual = QtWidgets.QAction(MainWindow)
self.actionManual.setObjectName("actionManual")
self.actionAuto = QtWidgets.QAction(MainWindow)
self.actionAuto.setObjectName("actionAuto")
self.actionSettings = QtWidgets.QAction(MainWindow)
self.actionSettings.setObjectName("actionSettings")
self.actionCalib = QtWidgets.QAction(MainWindow)
self.actionCalib.setObjectName("actionCalib")
self.actionDisconnect = QtWidgets.QAction(MainWindow)
self.actionDisconnect.setObjectName("actionDisconnect")
self.menuconnect.addAction(self.actionDisconnect)
self.menuDisconnect.addAction(self.actionSettings)
self.menuDisconnect.addAction(self.actionCalib)
self.menuMode.addAction(self.actionManual)
self.menuMode.addAction(self.actionAuto)
self.menuSensors.addAction(self.actionLIDAR)
self.menuSensors.addAction(self.actionOpen_CV)
self.menubar.addAction(self.menuconnect.menuAction())
self.menubar.addAction(self.menuDisconnect.menuAction())
self.menubar.addAction(self.menuMode.menuAction())
self.menubar.addAction(self.menuSensors.menuAction())
self.retranslateUi(MainWindow)
self.tabWidget.setCurrentIndex(1)
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_2.setText(_translate("MainWindow", "PushButton"))
self.pushButton_3.setText(_translate("MainWindow", "PushButton"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Tab 1"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Tab 2"))
self.menuconnect.setTitle(_translate("MainWindow", "connect"))
self.menuDisconnect.setTitle(_translate("MainWindow", "configure"))
self.menuMode.setTitle(_translate("MainWindow", "Mode"))
self.menuSensors.setTitle(_translate("MainWindow", "Sensors"))
self.actionLIDAR.setText(_translate("MainWindow", "LIDAR"))
self.actionOpen_CV.setText(_translate("MainWindow", "Open CV"))
self.actionManual.setText(_translate("MainWindow", "Manual"))
self.actionAuto.setText(_translate("MainWindow", "Auto"))
self.actionSettings.setText(_translate("MainWindow", "Settings"))
self.actionCalib.setText(_translate("MainWindow", "Calib"))
self.actionDisconnect.setText(_translate("MainWindow", "Disconnect"))
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 my gui code and i want to add the below file in the headswidget and the file name is hudsup.py :
import sys
import math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
def rec_line_cord(i,list,xc,origin_list,pitch,roll):
.
.
def rec_drawLine(self,i,list,painter,roll,metrics):
.
.
.
def drawMarkings(self, painter):
.
.
.
def drawNeedle(self, painter,roll):
.
.
.
def Compass(self,painter,yaw,r):
.
.
.
class Manager(QObject):
changedValue = pyqtSignal(tuple)
def __init__(self):
QObject.__init__(self)
filename = "Attitude_data_Manual_1232018_1158.txt"
res = self.read_content(filename)
self.results = zip(*res)
self.timer = QTimer(self)
self.timer.timeout.connect(self.update_value)
self.timer.start(100)
#pyqtSlot()
def update_value(self):
try:
self.changedValue.emit(next(self.results))
except StopIteration:
self.timer.stop()
def read_content(self, filename):
.
.
.
class Widget(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self, parent)
self.v = None
#pyqtSlot(tuple)
def update_value(self, v):
self.v = v
self.update()
def paintEvent(self, event):
QWidget.paintEvent(self, event)
painter = QPainter(self)
r = self.rect()
.
.
if __name__ == '__main__':
app = QApplication(sys.argv)
manager = Manager()
w = Widget()
manager.changedValue.connect(w.update_value)
w.show()
sys.exit(app.exec_())
This is my example of python script.
here is hudsup.py output :
animated huds_up display
and my ui looks like this and i want my hudsup to displayed as mentioned :
Gui
You should not use the generated code directly, instead, create a new widget class and inherit from it:
class MainWindow(Ui_MainWindow, QMainWindow):
def __init__(self):
Ui_MainWindow.__init__(self)
QMainWindow.__init__(self)
self.setupUi(self)
To integrate your second widget you can just add it to Heads_up like you are doing now but don't need to call exec_:
self.hud_sup = HudSup()
self.Heads_up.addWidget(self.hud_sup)

Resources