Pass dictionary of lists to Qtablewidget - PyQT5 - python-3.x

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))

Related

PyQt Can't open 3d dialog window and close the 1st one

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

Open one QMainWindow from another QMainWindow

I have problem with understanding how to open one QMainWindow from another. I want second window to open when the button in the first window is pressed. But I don't know how to do this because classes of the windows is written in the different way.
When I try just to import Main() class with the second window in the file with first window, second window starts to open when I run the first file and I don't even see the first window
First window:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def openWindow(self):
blank
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(600, 400)
MainWindow.setMinimumSize(QtCore.QSize(600, 400))
MainWindow.setMaximumSize(QtCore.QSize(600, 400))
font = QtGui.QFont()
font.setPointSize(16)
MainWindow.setFont(font)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.splitter = QtWidgets.QSplitter(self.centralwidget)
self.splitter.setGeometry(QtCore.QRect(170, 20, 260, 371))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.splitter.sizePolicy().hasHeightForWidth())
self.splitter.setSizePolicy(sizePolicy)
self.splitter.setOrientation(QtCore.Qt.Vertical)
self.splitter.setObjectName("splitter")
self.pushButton = QtWidgets.QPushButton(self.splitter)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().hasHeightForWidth())
self.pushButton.setSizePolicy(sizePolicy)
self.pushButton.setMaximumSize(QtCore.QSize(260, 90))
font = QtGui.QFont()
font.setPointSize(16)
self.pushButton.setFont(font)
self.pushButton.setObjectName("pushButton")
#self.pushButton.clicked.connect(self.openWindow)
#this is the button by pressing which i want to open second window
self.pushButton_2 = QtWidgets.QPushButton(self.splitter)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton_2.sizePolicy().hasHeightForWidth())
self.pushButton_2.setSizePolicy(sizePolicy)
self.pushButton_2.setMaximumSize(QtCore.QSize(260, 90))
font = QtGui.QFont()
font.setPointSize(16)
self.pushButton_2.setFont(font)
self.pushButton_2.setObjectName("pushButton_2")
self.pushButton_4 = QtWidgets.QPushButton(self.splitter)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton_4.sizePolicy().hasHeightForWidth())
self.pushButton_4.setSizePolicy(sizePolicy)
self.pushButton_4.setMaximumSize(QtCore.QSize(260, 90))
font = QtGui.QFont()
font.setPointSize(16)
self.pushButton_4.setFont(font)
self.pushButton_4.setObjectName("pushButton_4")
self.pushButton_3 = QtWidgets.QPushButton(self.splitter)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton_3.sizePolicy().hasHeightForWidth())
self.pushButton_3.setSizePolicy(sizePolicy)
self.pushButton_3.setMaximumSize(QtCore.QSize(260, 90))
font = QtGui.QFont()
font.setPointSize(16)
self.pushButton_3.setFont(font)
self.pushButton_3.setObjectName("pushButton_3")
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.pushButton.setText(_translate("MainWindow", "Просмотр базы"))
self.pushButton_2.setText(_translate("MainWindow", "Выдача/Принятие книг"))
self.pushButton_4.setText(_translate("MainWindow", "Внести книги в базу"))
self.pushButton_3.setText(_translate("MainWindow", "Редактировать список \nклассов"))
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_())
Second window:
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtPrintSupport import *
import sys
import sqlite3
import time
import os
from PyQt5 import QtCore, QtGui, QtWidgets
from test2 import Ui_Dialog
from searchdialog import Ui_Dialogg
from edit import Ui_Dialoge
class Main(QMainWindow):
def __init__(self, *args, **kwargs):
super(Main, self).__init__(*args, **kwargs)
self.conn = sqlite3.connect("booksbase.db")
self.c = self.conn.cursor()
self.c.execute("CREATE TABLE IF NOT EXISTS books(title TEXT,subject TEXT,grade INTEGER,author TEXT,year INTEGER, amount INTEGER)")
self.c.close()
self.setWindowTitle("Books base")
self.setMinimumSize(800, 600)
file_menu = self.menuBar().addMenu("&File")
help_menu = self.menuBar().addMenu("&About")
self.tableWidget = QTableWidget()
self.setCentralWidget(self.tableWidget)
self.tableWidget.setAlternatingRowColors(False)
self.tableWidget.setColumnCount(6)
self.tableWidget.horizontalHeader().setCascadingSectionResizes(False)
self.tableWidget.horizontalHeader().setSortIndicatorShown(False)
self.tableWidget.verticalHeader().setVisible(False)
self.tableWidget.verticalHeader().setCascadingSectionResizes(True)
self.tableWidget.verticalHeader().setStretchLastSection(False)
header = self.tableWidget.horizontalHeader()
header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(6, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(4, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(5, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch)
header.setSectionResizeMode(3, QtWidgets.QHeaderView.Stretch)
self.tableWidget.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers)
self.tableWidget.setHorizontalHeaderLabels(("Заголовок", "Предмет", "Класс", "Автор","Год", "Колличество"))
self.tableWidget.itemDoubleClicked.connect(self.print)
toolbar = QToolBar()
toolbar.setMovable(False)
self.addToolBar(toolbar)
statusbar = QStatusBar()
self.setStatusBar(statusbar)
btn_ac_adduser = QAction(QIcon("icon/add1.jpg"), "Add Student", self) #add student icon
btn_ac_adduser.triggered.connect(self.insert)
btn_ac_adduser.setStatusTip("Add Student")
toolbar.addAction(btn_ac_adduser)
btn_ac_search = QAction(QIcon("icon/s1.png"), "Search", self) #search icon
btn_ac_search.triggered.connect(self.search)
btn_ac_search.setStatusTip("Search User")
toolbar.addAction(btn_ac_search)
adduser_action = QAction(QIcon("icon/add1.jpg"),"Insert Student", self)
adduser_action.triggered.connect(self.insert)
file_menu.addAction(adduser_action)
searchuser_action = QAction(QIcon("icon/s1.png"), "Search Student", self)
searchuser_action.triggered.connect(self.search)
file_menu.addAction(searchuser_action)
about_action = QAction(QIcon("icon/i1.png"),"Developer", self) #info icon
about_action.triggered.connect(self.about)
help_menu.addAction(about_action)
def loaddata(self):
self.connection = sqlite3.connect("booksbase.db")
query = "SELECT * FROM books"
result = self.connection.execute(query)
self.tableWidget.setRowCount(0)
for row_number, row_data in enumerate(result):
self.tableWidget.insertRow(row_number)
for column_number, data in enumerate(row_data):
self.tableWidget.setItem(row_number, column_number, QTableWidgetItem(str(data)))
self.connection.close()
def insert(self):
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.exec_()
print("now")
self.loaddata()
def search(self):
Dialog = QtWidgets.QDialog()
ui = Ui_Dialogg()
ui.setupUi(Dialog)
Dialog.exec_()
def print(self):
row = self.tableWidget.currentRow()
col = self.tableWidget.item(row,0)
title = col.text()
col = self.tableWidget.item(row,1)
subject = col.text()
col = self.tableWidget.item(row,2)
grade = col.text()
col = self.tableWidget.item(row,3)
author = col.text()
col = self.tableWidget.item(row,4)
year = col.text()
col = self.tableWidget.item(row,5)
amount = col.text()
print(title, subject, grade, author, year, amount)
Dialog = QtWidgets.QDialog()
ui = Ui_Dialoge()
ui.setupUi(Dialog, title, subject, grade, author, year, amount)
Dialog.exec_()
self.loaddata()
app = QApplication(sys.argv)
if(QDialog.Accepted == True):
window = Main()
window.show()
window.loaddata()
sys.exit(app.exec_())
The problems resides in the fact that the file you are importing for the second window tries to run its last block:
app = QApplication(sys.argv)
if(QDialog.Accepted == True):
window = Main()
window.show()
window.loaddata()
sys.exit(app.exec_())
When a file (module) is imported, all of its executable statements are processed; in simple terms, everything that's "outside" a def is executed, including the module's own imports, function calls, try/except blocks, for/while loops, and all statements within any class definition.
Since you're checking against QDialog.Accepted (which is a constant), the statement is obviously true, then that if block is executed, resulting in the window being initialized and shown.
Remove that block from the second file and it will work as expected.
Two notes about that code, anyway:
there should exist one and only one QApplication instance for each PyQt based program; the above code could actually crash in most cases because of that;
as said before, QDialog.Accepted is a constant, and it's value is 1, so that if statements doesn't make much sense (it would have been the same as if True == True:); that constant, along with its opposite QDialog.Rejected, is normally used only when checked against the return value of a QDialog.exec() call.

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)

Python - PyQt5 how to take file as a input?

There is screenshot attached below:So basically i want to take file as a input(i.e suffix_list.txt) instead of specifying file location inside the function and when i clicked action button i need execute a output inside QtTextEdit
I tried something but i can't get it. Please help me out. I'm new to PyQt5Thanks
This is my gui code:
# -*- coding: utf-8 -*-
# Created by: PyQt5 UI code generator 5.10
#
# 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(514, 381)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.text_output = QtWidgets.QTextEdit(self.centralwidget)
self.text_output.setGeometry(QtCore.QRect(80, 10, 351, 271))
self.text_output.setObjectName("text_output")
self.btn_Action = QtWidgets.QPushButton(self.centralwidget)
self.btn_Action.setGeometry(QtCore.QRect(220, 300, 75, 23))
self.btn_Action.setObjectName("btn_Action")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 514, 21))
self.menubar.setObjectName("menubar")
self.menuFile = QtWidgets.QMenu(self.menubar)
self.menuFile.setObjectName("menuFile")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.actionOpen_File = QtWidgets.QAction(MainWindow)
self.actionOpen_File.setObjectName("actionOpen_File")
self.menuFile.addAction(self.actionOpen_File)
self.menubar.addAction(self.menuFile.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.btn_Action.setText(_translate("MainWindow", "Action"))
self.menuFile.setTitle(_translate("MainWindow", "File"))
self.actionOpen_File.setText(_translate("MainWindow", "Open File"))
def file_open(self):
name, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Open File', options=QtWidgets.QFileDialog.DontUseNativeDialog)
file = open(name, 'r')
with file:
text = file.read()
self.textEdit.setText(text)
def suffix_remove(self):
suffix_list = []
dictionary = {}
lists = ['athletic','kitchenette','helpful','terrify']
with open('suffix_list.txt') as f:
for lines in f:
lines = lines.rstrip()
suffix_list.append(lines)
for words in lists:
for suffix in suffix_list:
if words.endswith(suffix):
final_list = str.replace(words,suffix,'')
dictionary[words] = final_list
return dictionary
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
ui.btn_Action.clicked.connect(lambda:
ui.text_output.append(str(ui.suffix_remove())))
MainWindow.show()
sys.exit(app.exec_())
The two main problems you have are that you do not call your file_open method and you are supplying an instance of Ui_MainWindow to your file dialog when it needs to be an instance of MainWindow. Here is how to fix this:
def retranslateUi(self, MainWindow):
self.main_window = MainWindow
# your code here
self.actionOpen_File.triggered.connect(self.file_open)
def file_open(self):
name, _ = QtWidgets.QFileDialog(self.main_window, 'Open File', options=QtWidgets.QFileDialog.DontUseNativeDialog)
# your code here
There are, however, some problems outside the scope of this question in your code structure that will make this difficult to expand upon.
Thanks everyone <
Here is my answer what i actually want to do.
# -*- coding: utf-8 -*-
# Created by: PyQt5 UI code generator 5.10
#
# 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(514, 381)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.text_output = QtWidgets.QTextEdit(self.centralwidget)
self.text_output.setGeometry(QtCore.QRect(80, 10, 351, 271))
self.text_output.setObjectName("text_output")
self.btn_Action = QtWidgets.QPushButton(self.centralwidget)
self.btn_Action.setGeometry(QtCore.QRect(220, 300, 75, 23))
self.btn_Action.setObjectName("btn_Action")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 514, 21))
self.menubar.setObjectName("menubar")
self.menuFile = QtWidgets.QMenu(self.menubar)
self.menuFile.setObjectName("menuFile")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.actionOpen_File = QtWidgets.QAction(MainWindow)
self.actionOpen_File.setObjectName("actionOpen_File")
self.actionOpen_File.setShortcut('Ctrl+O')
self.actionOpen_File.triggered.connect(self.file_open)
self.menuFile.addAction(self.actionOpen_File)
self.menubar.addAction(self.menuFile.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.btn_Action.setText(_translate("MainWindow", "Action"))
self.menuFile.setTitle(_translate("MainWindow", "File"))
self.actionOpen_File.setText(_translate("MainWindow", "Open File"))
def file_open(self):
name, _ = QtWidgets.QFileDialog.getOpenFileName(None, 'Open File', options=QtWidgets.QFileDialog.DontUseNativeDialog)
file = open(name, 'r')
with file:
text = file.read()
self.text_output.setText(text)
def suffix_remove(self):
suffix_list = []
dictionary = {}
lists = ['athletic','kitchenette','helpful','terrify']
f = self.text_output.toPlainText()
for lines in f:
lines = lines.rstrip()
suffix_list.append(lines)
for words in lists:
for suffix in suffix_list:
if words.endswith(suffix):
final_list = str.replace(words,suffix,'')
dictionary[words] = final_list
return dictionary
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
ui.btn_Action.clicked.connect(lambda: ui.text_output.append(str(ui.suffix_remove())))
MainWindow.show()
sys.exit(app.exec_())

Redraw main window in pyQT5 on update

I am trying to redraw my screen after an action.
Basically I am showing a list of labels to print, when a label is printed, or the refresh button is clicked, all child widgets should be removed and the database query will pull in the new ones.
here is my code, I am struggling with the function def refresh, I am new to qt and using python3
from functools import partial
import cups
from PyQt5 import QtCore, QtWidgets
import barcode
from barcode.writer import ImageWriter
import sql
class Ui_MainWindow(object):
def __init__(self):
self.centralwidget = QtWidgets.QWidget(MainWindow)
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1024, 600)
self.centralwidget.setObjectName("centralwidget")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(910, 10, 90, 28))
self.pushButton.setObjectName("pushButton")
self.scrollArea = QtWidgets.QScrollArea(self.centralwidget)
self.scrollArea.setGeometry(QtCore.QRect(0, 50, 1027, 541))
self.scrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.scrollArea.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.scrollArea.setWidgetResizable(False)
self.scrollArea.setObjectName("scrollArea")
self.scrollAreaWidgetContents = QtWidgets.QWidget()
rows = len(sql.get_prepacks()) / 5
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 1027, rows * 280))
self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
MainWindow.setCentralWidget(self.centralwidget)
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Prepack Print Station"))
self.pushButton.setText(_translate("MainWindow", "Reload"))
self.pushButton.clicked.connect(self.on_click)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.show_cartons()
def on_click(self):
self.refresh()
def show_cartons(self):
i = 0
z = 20
y = 20
pre_packs = sql.get_prepacks()
for p in pre_packs:
pz = 35
py = 30
# Box
self.frame = QtWidgets.QFrame(self.scrollAreaWidgetContents)
self.frame.setGeometry(QtCore.QRect(z, y, 150, 200))
self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
# Prepack ID
self.label = QtWidgets.QLabel(self.frame)
self.label.setGeometry(QtCore.QRect(pz, py, 100, 20))
self.label.setText(str(p[0]))
py = py + 40
# Altcode
self.label_2 = QtWidgets.QLabel(self.frame)
self.label_2.setGeometry(QtCore.QRect(pz, py, 100, 20))
self.label_2.setText(str(p[1]))
py = py + 40
# Colour
self.label_3 = QtWidgets.QLabel(self.frame)
self.label_3.setGeometry(QtCore.QRect(pz, py, 100, 20))
self.label_3.setText(str(p[2]))
py = py + 40
# Button
self.p_button = QtWidgets.QPushButton(self.frame)
self.p_button.setGeometry(QtCore.QRect(10, py, 130, 40))
self.p_button.setText("Print " + str(p[3]) + " Labels")
self.p_button.clicked.connect(partial(self.print_clicked, str(p[0])))
z = z + 180
i = i + 1
if i == 5:
z = 20
i = 0
y = y + 230
def print_clicked(self, pp):
labels = sql.get_labelsforprepack(pp)
conn = cups.Connection()
totallabels = len(labels)
alloccode = labels[0][1]
bcode = barcode.get('code39', str(alloccode), writer=ImageWriter())
filename = bcode.save('bcode')
conn.printFile("USB", filename, "Test", {"copies": str(totallabels)})
sql.insert_print_record(alloccode)
for l in labels:
sql.insert_carton(str(l[0]), str(l[1]))
self.refresh()
def refresh(self):
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.repaint()
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_())
UPDATE -> I am a little closer using this:
def refresh(self):
for i in self.scrollAreaWidgetContents.children():
sip.delete(i)
self.show_cartons()
self.scrollAreaWidgetContents.repaint()
The frames are now deleted, but calling show_cartons() doesn't readd them, add .repaint is not working either
And this is how I did it in the end
import os
from functools import partial
import cups
import sip
import time
from PyQt5 import QtCore, QtWidgets
import barcode
from barcode.writer import ImageWriter
import sql
class Ui_MainWindow(object):
def setupBasics(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1024, 600)
MainWindow.setWindowTitle("Prepack Print Station")
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(910, 10, 90, 28))
self.pushButton.setObjectName("pushButton")
self.pushButton.setText("Reload")
self.pushButton.clicked.connect(self.on_click)
self.scrollArea = QtWidgets.QScrollArea(self.centralwidget)
self.scrollArea.setGeometry(QtCore.QRect(0, 50, 1027, 541))
self.scrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.scrollArea.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.scrollArea.setWidgetResizable(False)
self.scrollArea.setObjectName("scrollArea")
MainWindow.setCentralWidget(self.centralwidget)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.setupDynamics()
def setupDynamics(self):
self.scrollAreaWidgetContents = QtWidgets.QWidget()
rows = len(sql.get_prepacks()) / 5
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 1027, rows * 280))
self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
self.show_cartons()
def on_click(self):
self.refresh()
def show_cartons(self):
i = 0
z = 20
y = 20
pre_packs = sql.get_prepacks()
for p in pre_packs:
pz = 35
py = 30
# Box
self.frame = QtWidgets.QFrame(self.scrollAreaWidgetContents)
self.frame.setGeometry(QtCore.QRect(z, y, 150, 200))
self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
# Prepack ID
self.label = QtWidgets.QLabel(self.frame)
self.label.setGeometry(QtCore.QRect(pz, py, 100, 20))
self.label.setText(str(p[0]))
py = py + 40
# Altcode
self.label_2 = QtWidgets.QLabel(self.frame)
self.label_2.setGeometry(QtCore.QRect(pz, py, 100, 20))
self.label_2.setText(str(p[1]))
py = py + 40
# Colour
self.label_3 = QtWidgets.QLabel(self.frame)
self.label_3.setGeometry(QtCore.QRect(pz, py, 100, 20))
self.label_3.setText(str(p[2]))
py = py + 40
# Button
self.p_button = QtWidgets.QPushButton(self.frame)
self.p_button.setGeometry(QtCore.QRect(10, py, 130, 40))
self.p_button.setText("Print " + str(p[3]) + " Labels")
self.p_button.clicked.connect(partial(self.print_clicked, str(p[0])))
z = z + 180
i = i + 1
if i == 5:
z = 20
i = 0
y = y + 230
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.scrollArea.repaint()
def print_clicked(self, pp):
labels = sql.get_labelsforprepack(pp)
conn = cups.Connection()
totallabels = len(labels)
alloccode = labels[0][1]
bcode = barcode.get('code39', str(alloccode), writer=ImageWriter())
filename = bcode.save('bcode')
conn.printFile("USB", filename, "Test", {"copies": str(totallabels)})
sql.insert_print_record(alloccode)
for l in labels:
sql.insert_carton(str(l[0]), str(l[1]))
self.refresh()
def refresh(self):
d = self.scrollAreaWidgetContents.children()
e = reversed(d)
for g in e:
g.deleteLater()
self.scrollAreaWidgetContents.deleteLater()
self.setupDynamics()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupBasics(MainWindow)
MainWindow.show()
sys.exit(app.exec_())

Resources