I want to access a list created on my main window based on user selection, on my second window.
the list was created in MainWindow under the on_cc_pick method. List creditcards.
on the second window, I would like to access it on CreditCardForm
When i try.MainWindow.creditcards or MainWindow.creditcardsb it tells me object has no attribute creditcards/b.
When I try doing a global variable under MainWindow Class:
class MainWindow(QtWidgets.QWidget):
creditcards = []
it always defaults to an empty list.
here is my code, in essence I want to access the list called creditcardsb created on class MainWindow under def on_cc_pick(self,text): on class CreditCardForm under def savecsv(self):
class AddCreditCard(QtWidgets.QMainWindow):
def __init__(self, parent = None):
super(AddCreditCard, self).__init__(parent)
creditcardform = CreditCardForm(self)
self.setCentralWidget(creditcardform)
class CreditCardForm(QtWidgets.QWidget):
def savecsv(self):
**print(MainWindow.creditcardsb)**
def __init__(self, parent):
super(CreditCardForm, self).__init__(parent)
self.addname = QtWidgets.QPushButton('Save')
self.connect(self.addname,QtCore.SIGNAL("clicked()"), self.savecsv)
class MainWindow(QtWidgets.QWidget):
def CreateCCForm(self):
self.addwindow.show()
def on_cc_pick(self, text):
NickName = []
Account = []
with open(refdirectory + '/' + str(text) + '.csv') as csvDataFile:
csvReader = csv.reader(csvDataFile)
for row in csvReader:
NickName.append(row[0])
Account.append(row[1])
**creditcardsb = list(zip(NickName,Account))
self.creditcards = creditcardsb**
def __init__(self, parent = None):
super(MainWindow,self).__init__(parent)
self.pickcard = QtWidgets.QComboBox(self)
CreditCardNames = ['cc1','cc2','cc3']
for cc in CreditCardNames:
self.pickcard.addItem(cc)
self.addcard = QtWidgets.QPushButton('Add Card')
self.pickcard.activated[str].connect(self.on_cc_pick)
self.connect(self.addcard, QtCore.SIGNAL("clicked()"),self.CreateCCForm)
self.addwindow = AddCreditCard(self)
These are the imports I am using, not all relatable to my issue:
from subprocess import Popen
from selenium import webdriver
from bs4 import BeautifulSoup
import string
import time
import random
import csv
import pandas as pd
from pick import pick
import requests
import re
import urllib.request
from urllib.request import urlopen
from selenium.webdriver.common.by import By
from tkinter import *
import tkinter as tk
import tkinter.filedialog as filedialog
import os
import pyodbc
from decimal import *
import sys
from PySide2 import QtCore, QtGui, QtWidgets
from datetime import datetime, date
from decimal import Decimal
Do not use static variables since the property you want to transmit depends not on the class but on the objects. So the correct thing is to create a method that updates the data of the window. In addition, assuming that CreditCardForm will always be a child of AddCreditCard, you can obtain AddCreditCard using parentWidget() from CreditCardForm.
import os
import csv
from PySide2 import QtCore, QtWidgets
class AddCreditCard(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(AddCreditCard, self).__init__(parent)
creditcardform = CreditCardForm()
self.setCentralWidget(creditcardform)
self._creditcards = []
def setCreditcards(self, creditcards):
self._creditcards = creditcards
def creditcards(self):
return self._creditcards
class CreditCardForm(QtWidgets.QWidget):
def __init__(self, parent=None):
super(CreditCardForm, self).__init__(parent)
self.addname = QtWidgets.QPushButton('Save')
self.addname.clicked.connect(self.savecsv)
lay = QtWidgets.QHBoxLayout(self)
lay.addWidget(self.addname)
#QtCore.Slot()
def savecsv(self):
creditcards = self.parentWidget().creditcards()
print(creditcards)
class MainWindow(QtWidgets.QWidget):
def __init__(self, parent = None):
super(MainWindow,self).__init__(parent)
self.addwindow = AddCreditCard(self)
self.pickcard = QtWidgets.QComboBox()
self.pickcard.activated[str].connect(self.on_cc_pick)
creditcardnames = ['cc1','cc2','cc3']
self.pickcard.addItems(creditcardnames)
self.addcard = QtWidgets.QPushButton('Add Card')
self.addcard.clicked.connect(self.addwindow.show)
lay = QtWidgets.QVBoxLayout(self)
lay.addWidget(self.addcard)
lay.addWidget(self.pickcard)
#QtCore.Slot(str)
def on_cc_pick(self, text):
creditcards = []
refdirectory = ""
filename = os.path.join(refdirectory, "{}.csv".format(text))
with open(filename) as csvDataFile:
csvReader = csv.reader(csvDataFile)
for row in csvReader:
creditcards.append((row[0], row[1]))
self.addwindow.setCreditcards(creditcards)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
Related
I have opened the file from the current directory in "opened" method, here file is opening and reading the data in it, but I want to write the read data in MDI subwindow.
from PyQt5 import QtWidgets
from PyQt5 import QtGui
from PyQt5 import QtCore
from PyQt5.QtWidgets import QMdiArea, QMdiSubWindow
from PyQt5.Qt import QMenu
import os
import tree2
class fileview(tree2.Ui_FOSApplication,QtWidgets.QMainWindow):
count = 0
def __init__(self):
super(fileview, self).__init__()
self.setupUi(self)
self.treeView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.treeView.customContextMenuRequested.connect(self.context_view)
self.populate()
def populate(self):
path = 'C:\FOS Application'
self.model = QtWidgets.QFileSystemModel()
self.model.setRootPath(QtCore.QDir.rootPath())
self.treeView.setModel(self.model)
self.treeView.setRootIndex(self.model.index(path))
#self.treeView.doubleClicked.connect(self.context_view)
#self.treeView.setSortingEnabled(True)
self.treeView.setColumnHidden(1, True)
self.treeView.setColumnHidden(2, True)
self.treeView.setColumnHidden(3, True)
def context_view(self):
view = QtWidgets.QMenu()
open = view.addAction("Open")
open.triggered.connect(self.subwindow)
curser = QtGui.QCursor()
view.exec_(curser.pos())
def subwindow(self):
fileview.count = fileview.count+1
self.w = self.openfile()
self.sub = QMdiSubWindow()
self.sub.setWidget(self.w)
#self.mdiArea.activeSubWindow(self.sub)
self.mdiArea.addSubWindow(self.sub)
self.sub.show()
def openfile(self):
index = self.treeView.currentIndex()
file_name = self.model.filePath(index)
os.startfile(file_name)
if __name__ == '__main__':
app = QtWidgets.QApplication([])`enter code here`
fb = fileview()
fb.show()
app.exec_()
I am trying to create a gallery view in PyQT5. I am currently trying to group the photos (grey boxes) in months as seen below. I am reading the file location and the date taken of the images through a SQL database.
So far I have managed to lazy load all of the images into the QtWidgets.QListView using a basic model, seen below. I have never worked with PyQt before and I am getting a little lost. Can anyone help me?
import sys
import CustomWidgets as cw
import platform
from PyQt5 import QtCore, QtGui, QtWidgets
import os
import threading
import math
import pyodbc
# GUI FILE
from PhotosPage import Ui_MainWindow
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
QtWidgets.QMainWindow.__init__(self)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
# connect tab Pages
self.ui.PageButton_Photos.clicked.connect(lambda: self.ui.stackedWidget.setCurrentWidget(self.ui.PhotosPage))
self.ui.PageButton_Albums.clicked.connect(lambda: self.ui.stackedWidget.setCurrentWidget(self.ui.AlbumsPage))
self.ui.PageButton_People.clicked.connect(lambda: self.ui.stackedWidget.setCurrentWidget(self.ui.PeoplePage))
self.ui.PageButton_Groups.clicked.connect(lambda: self.ui.stackedWidget.setCurrentWidget(self.ui.GroupsPage))
# hide Album info
self.ui.AlbumInfoFrame.hide()
# set model for photos
model = TestListModel(self.ui.PhotosFrame)
self.ui.PhotosFrame.setModel(model)
self.ui.PhotosFrame.setSpacing(5)
self.show()
class TestListModel(QtCore.QAbstractListModel):
def __init__(self, parent=None):
QtCore.QAbstractListModel.__init__(self, parent)
self.list = parent
self.fileList = os.listdir('P:/PhotoSorterInfo/MiniPhotos')
# self.setFileList()
def setFileList(self):
print(self.readDataBase()[0])
def rowCount(self, index):
return len(self.fileList)
def data(self, index, role):
if role == QtCore.Qt.DisplayRole:
if not self.list.indexWidget(index):
button = QtWidgets.QPushButton()
button.setIcon(QtGui.QIcon("P:/PhotoSorterInfo/MiniPhotos/" + self.fileList[index.row()]))
button.setIconSize(QtCore.QSize(300, 175))
button.setFlat(True)
self.list.setIndexWidget(index, button)
return QtCore.QVariant()
if role == QtCore.Qt.SizeHintRole:
return QtCore.QSize(300, 175)
def columnCount(self, index):
pass
def readDataBase(self, id=10):
returnInfo = DataBase.execute(
"""SELECT Files_tbl.ID, Files_tbl.Name, Files_tbl.FileType, Files_tbl.Width, Files_tbl.Height, Files_tbl.Size, Files_tbl.DateTaken, FileDirectories_tbl.FileLocation
FROM Files_tbl, FileDirectories_tbl
WHERE FileDirectories_tbl.ID = Files_tbl.FileLocation
ORDER BY DateTaken DESC;""")
# place info into dictionary
Photos = []
results = []
columns = [column[0] for column in DataBase.description]
for row in returnInfo.fetchall():
Photos.append(dict(zip(columns, row)))
return Photos
if __name__ == "__main__":
filePath = os.getcwd()
DataBase = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=' + filePath + r'\Database\PhotosDatabase.accdb;')
DataBase = DataBase.cursor()
import sys
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec_())
I have created the ui for my application using Qt Designer. The UI includes two Widgets. A dropdown (ComboBox) with different values each representing a year (2015, 2025, 2035) and a custom widget that loads a shapefile on a map: Here is a screenshot of the UI (
Also, here is library.ui file) :
Here is my index.py file to connect to ui:
import sys
from os import environ
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.uic import loadUiType
ui,_=loadUiType('library.ui')
def suppress_qt_warnings():
environ["QT_DEVICE_PIXEL_RATIO"] = "0"
environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1"
environ["QT_SCREEN_SCALE_FACTORS"] = "1"
environ["QT_SCALE_FACTOR"] = "1"
class MainApp(QMainWindow, ui):
def __init__(self):
QMainWindow.__init__(self)
self.setupUi(self)
def main():
suppress_qt_warnings()
app=QApplication(sys.argv)
window = MainApp()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
and here is the file associated with my custom widget (leafwidget.py):
import folium
import os.path
from PyQt5 import QtCore, QtWebEngineWidgets
from PyQt5.QtWidgets import *
import geopandas as gpd
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
class LeafWidget (QWidget):
def __init__(self, parent=None):
QWidget.__init__(self, parent)
self.view = QtWebEngineWidgets.QWebEngineView()
shp_filename = os.path.join(CURRENT_DIR, "input", '2015_loaded_NoCC.dbf')
shp_file = gpd.read_file(shp_filename)
shp_file_json_str = shp_file.to_json()
m = folium.Map(location=[39.764075, -86.159019], zoom_start=10)
folium.GeoJson(shp_file_json_str).add_to(m)
tmp_file = QtCore.QTemporaryFile("net.html", self)
if tmp_file.open():
m.save(tmp_file.fileName())
url = QtCore.QUrl.fromLocalFile(tmp_file.fileName())
self.view.load(url)
lay = QVBoxLayout(self)
lay.addWidget(self.view)
self.show()
As you can see in my custom widget Class (LeafWidget), the dbf file's name starts with the year value (2015, 2025, 2035) followed by "_loaded_NocCC.dbf" (for example "2015_loaded_NoCC.shp" and so on).
Now, I need to access the selected value from the dropdown list (let's say 2025) and then display the corresponding shapefile in the map (2025_loaded_NoCC.shp).
I can access the value of ComboBox easily using self.ComboBox.currentText() inside index.py, but in the leafletwidget class (leafwidget.py), I don't have access to self.ComboBox.currentText() and get the error that basically my Class has no attribute "ComboBox".
SO, how can I access the value of ComboBox in my LeafWidget class?
You have to create a method that updates the shapefile that will be shown, and call that method every time a new option is chosen generating the new path:
import folium
from PyQt5 import QtCore, QtWebEngineWidgets
from PyQt5.QtWidgets import *
import geopandas as gpd
class LeafWidget(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self, parent)
self.view = QtWebEngineWidgets.QWebEngineView()
lay = QVBoxLayout(self)
lay.addWidget(self.view)
self.tmp_file = QtCore.QTemporaryFile("XXXXXX.html")
def set_shapefile(self, filename):
shp_file = gpd.read_file(filename)
shp_file_json_str = shp_file.to_json()
m = folium.Map(location=[39.764075, -86.159019], zoom_start=10)
folium.GeoJson(shp_file_json_str).add_to(m)
if self.tmp_file.open():
m.save(self.tmp_file.fileName())
url = QtCore.QUrl.fromLocalFile(self.tmp_file.fileName())
self.view.load(url)
import sys
import os.path
from os import environ
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.uic import loadUiType
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
ui, _ = loadUiType(os.path.join(CURRENT_DIR, "library.ui"))
def suppress_qt_warnings():
environ["QT_DEVICE_PIXEL_RATIO"] = "0"
environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1"
environ["QT_SCREEN_SCALE_FACTORS"] = "1"
environ["QT_SCALE_FACTOR"] = "1"
class MainApp(QMainWindow, ui):
def __init__(self):
QMainWindow.__init__(self)
self.setupUi(self)
self.comboBox.currentTextChanged.connect(self.handle_currentTextChanged)
self.handle_currentTextChanged(self.comboBox.currentText())
def handle_currentTextChanged(self, text):
filename = shp_filename = os.path.join(
CURRENT_DIR, "input", "{}_loaded_NoCC.shp".format(text)
)
self.LeafWidget.set_shapefile(filename)
def main():
suppress_qt_warnings()
app = QApplication(sys.argv)
window = MainApp()
window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
I have a running application that will take a CSV file and take out all the email addresses and display them on a QTableWidget. Unfortunately, it is only capable of doing this once. If I go back to select another CSV file the email TableWidget won't update, and the parameters will carry over to EmailList. This is also why I cannot init_ui in the constructer method of EmailList. I was wondering how the display can be updated, repeatedly with new file input. Here is an appropriate CSV file to run yourself. http://www.sharecsv.com/s/ed7c7a2154478339603a192921a352eb/csv_test.csv
email_list.py
import sys
import os
import re
import io
from construct import ConstructMessage
from PyQt5.QtWidgets import QFileDialog, QTableWidget,QTableWidgetItem, QVBoxLayout,QHBoxLayout, QWidget, QAction, QPushButton
from PyQt5.QtCore import Qt, pyqtSignal, QFileInfo, QDir
class EmailList(QWidget):
buttonClicked = pyqtSignal()
email_list = []
def __init__(self):
super().__init__()
print("Initzd")
#self.init_ui()
def init_ui(self):
self.v_layout = QVBoxLayout()
self.h_layout = QHBoxLayout()
self.email_widget = QTableWidget()
self.email_widget.setColumnCount(1)
for row_data in EmailList.email_list:
print("Email list: " + row_data)
row = self.email_widget.rowCount()
self.email_widget.insertRow(row)
for column, col in enumerate(row_data):
item = QTableWidgetItem(row_data)
self.email_widget.setItem(row, column, item)
width = 200
self.open_button = QPushButton("Open")
self.open_button.setMaximumWidth(width)
self.continue_button = QPushButton("Continue")
self.continue_button.setMaximumWidth(width)
self.back_button = QPushButton("Go back")
self.back_button.setMaximumWidth(width)
self.open_button.clicked.connect(lambda: self.open_click(self.open_button,"Open",self.widget))
self.continue_button.clicked.connect(lambda: self.continue_click(self.continue_button,"Continue"))
self.back_button.clicked.connect(lambda: self.on_back_clicked())
self.v_layout.addWidget(self.email_widget)
self.h_layout.addWidget(self.open_button)
self.h_layout.addWidget(self.continue_button)
self.h_layout.addWidget(self.back_button)
self.v_layout.addLayout(self.h_layout)
self.setLayout(self.v_layout)
self.setWindowTitle("Email List")
print("Welcome to the email_list widget")
self.show()
def on_back_clicked(self):
print("You are going back")
self.buttonClicked.emit()
def update_emails(self, imported_email_list):
EmailList.email_list = imported_email_list
def continue_click(self,continue_button,string):
pass
from sheet import Sheet
sheet.py
import sys
import os
import re
import io
import csv
from PyQt5.QtWidgets import QFileDialog, QTableWidget, QTableWidgetItem, QVBoxLayout,QHBoxLayout, QWidget, QAction, QPushButton
from PyQt5.QtCore import Qt, pyqtSignal, QFileInfo, QDir
class Sheet(QWidget):
buttonClicked = pyqtSignal()
email_list = []
def __init__(self,r,c):
super().__init__()
self.init_ui(r,c)
def init_ui(self,r,c):
self.v_layout = QVBoxLayout()
self.h_layout = QHBoxLayout()
self.sheet = QTableWidget()
self.sheet.setRowCount(r)
self.sheet.setColumnCount(c)
width = 200
self.open_button = QPushButton("Open")
self.open_button.setMaximumWidth(width)
self.continue_button = QPushButton("Continue")
self.continue_button.setMaximumWidth(width)
self.file_path = None
self.open_button.clicked.connect(lambda: self.open_click(self.open_button,"Open",self.sheet))
self.continue_button.clicked.connect(lambda: self.continue_click(self.continue_button,"Continue"))
self.v_layout.addWidget(self.sheet)
self.h_layout.addWidget(self.open_button)
self.h_layout.addWidget(self.continue_button)
self.v_layout.addLayout(self.h_layout)
self.setLayout(self.v_layout)
self.setWindowTitle("CSV Reader")
self.show()
def continue_click(self,continue_button,string):
self.buttonClicked.emit()
def open_click(self,open_button,string,sheet):
self.path = QFileDialog.getOpenFileName(self, 'Open CSV', os.getenv('HOME'), 'CSV(*.csv)')
if self.path[0] != '':
with open(self.path[0], 'rU') as csv_file:
self.sheet.setRowCount(0)
my_file = csv.reader(csv_file, delimiter=',', quotechar='|')
for row_data in my_file:
row = self.sheet.rowCount()
self.sheet.insertRow(row)
self.sheet.setColumnCount(len(row_data))
for column, col in enumerate(row_data):
item = QTableWidgetItem(col)
self.sheet.setItem(row, column, item)
self.file_path = self.path[0]
Sheet.email_list = re.findall(r'[\w_]+#[\w_]+\.[\w_]+', open(self.file_path).read())
EmailList.update_emails(self, Sheet.email_list)
from email_list import EmailList
and finally main.py
import sys
import os
import io
from sheet import Sheet
from email_list import EmailList
from PyQt5.QtWidgets import QApplication, QMainWindow, QStackedWidget
from PyQt5.QtCore import Qt
class Main(QMainWindow):
def __init__(self):
super().__init__()
self.central_widget = QStackedWidget()
self.setCentralWidget(self.central_widget)
self.sheet_widget = Sheet(10,10)
self.email_list_widget = EmailList()
self.central_widget.addWidget(self.sheet_widget)
self.central_widget.addWidget(self.email_list_widget)
self.central_widget.setCurrentWidget(self.sheet_widget)
self.sheet_widget.buttonClicked.connect(lambda: self.central_widget.setCurrentWidget(self.email_list_widget))
self.sheet_widget.buttonClicked.connect(self.email_list_widget.init_ui)
self.email_list_widget.buttonClicked.connect(lambda: self.central_widget.setCurrentWidget(self.sheet_widget))
app = QApplication(sys.argv)
run = Main()
run.resize(500,500)
run.show()
sys.exit(app.exec_())
Any help or insight on seamlessly updating a UI from a widget across module would be super! I was thinking of a refresh method, but the email_list already gets updated. The UI should update by itself but it's not, and I am missing something.
Problems with Qt How to open 2 windows that are called between them
Hi all, I'm new with Qt, the problem I have is the following:
I have a Login.py window when I call with a button open a new Panel_administrator.py window and this window has a button that can call Login.py
in a nutshell:
Login.py---->calls -----> Panel_Administrador.py and
Panel_Administrador.py ----> calls ----> Login.py
Gives me the following error:
Traceback (most recent call last):
.................
ImportError: cannot import name 'panel_administrador'
my code:
import sys
import time
from PyQt5 import uic
from PyQt5.QtWidgets import QApplication, QWidget
import Con_pos
from Registro import Registro
from Panel_Administrador import panel_administrador
class Login(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self, parent= parent)
uic.loadUi("UI/Login.ui", self)
self.registro.clicked.connect(self.view_Registro)
self.ingresar.clicked.connect(self.autenticar)
def autenticar(self):
pid = self.getPID()
con = Con_pos.con_pos()
user = self.in_login.text()
password = self.in_pass.text()
fecha = time.strftime("%X") + " " + time.strftime("%x")
if user != "" and password != "":
consulta = ''' SELECT "id_usuario" FROM "usuarios"."Usuario" WHERE "id_usuario" = '%s' ; ''' %(user)
c_user = con.consulta(consulta)
consulta = ''' SELECT "pass" FROM "usuarios"."Usuario" WHERE "id_usuario" = '%s' ;''' %(user)
c_pass = con.consulta(consulta)
if c_user != None or not c_pass:
c_pass = c_pass[0][0]
if c_pass == password:
consulta = ''' INSERT INTO "usuarios"."sesion" VALUES ('%s', '%s', %s); '''%(user ,fecha, pid)
con.insertar(consulta)
print("Ingresando al sistema...")
if self.administrador(user):
self.admi = panel_administrador()
self.admi.show()
else:
print("Usuario o password incorrecto")
def administrador(self, user):
ad = ''' SELECT "id_rol" FROM "usuarios"."Rol" WHERE "rol" = 'administrador'; '''
consulta = ''' SELECT "id_usuario_Usuario" FROM "usuarios"."Usuario_Rol" WHERE "id_rol_Rol" = %s and "id_usuario_Usuario" = '%s' ''' %(ad, user)
con_res = Con_pos.con_pos().consulta(consulta)
print(con_res)
if con_res or con_res != None:
return True
else:
return False;
def getPID(self):
con = Con_pos.con_pos()
func = "pg_backend_pid"
pid = con.call_proc(func)
pid = pid[0][0]
return pid
def view_Registro(self):
self.reg = Registro()
self.reg.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
login = Login()
login.show()
sys.exit(app.exec())
Panel_Administrador.py
import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QApplication, QWidget
from Designar import designar
from Funciones import funciones
from Login import Login
from Admi_Users import admin_user
from Rol import rol
class panel_administrador(QWidget):
def __init__(self):
QWidget.__init__(self)
uic.loadUi("UI/Panel_Administrador.ui", self)
self.btn_funciones.clicked.connect(self.view_funciones)
self.btn_roles.clicked.connect(self.view_roles)
self.btn_usuarios.clicked.connect(self.view_usuario)
self.btn_designar.clicked.connect(self.view_designar)
self.btn_login.clicked.connect(self.view_login)
def view_funciones(self):
self.f = funciones()
self.f.show()
def view_roles(self):
self.r = rol()
self.r.show()
def view_usuario(self):
self.u = admin_user()
self.u.show()
def view_designar(self):
self.d = designar()
self.d.show()
def view_login(self):
self.l = Login()
self.l.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
pa = panel_administrador()
pa.show()
sys.exit(app.exec())
The problem that occurs is called circular import, where it generates a recursive cycle. The solution is to structure the code better. In this case I will show an example of how to do it, I will create 2 classes called admin panel and Login that contains a button each, the object is to call the other window and vice versa. Create another file that I will call main.py where I will make the connections between the buttons.
The files have the following structure:
├── Login.py
├── main.py
└── Panel_Administrador.py
Login.py
from PyQt5.QtWidgets import QWidget, QPushButton, QVBoxLayout
class Login(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self, parent= parent)
self.setWindowTitle("Login")
lay = QVBoxLayout(self)
self.btn = QPushButton("LLamar a Panel Administrador")
lay.addWidget(self.btn)
self.btn.clicked.connect(self.hide)
Panel_Administrador.py
from PyQt5.QtWidgets import QWidget, QPushButton, QVBoxLayout
class panel_administrador(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self, parent=parent)
self.setWindowTitle("Panel de Administración")
lay = QVBoxLayout(self)
self.btn = QPushButton("Llamar a Login")
lay.addWidget(self.btn)
self.btn.clicked.connect(self.hide)
main.py
from PyQt5.QtWidgets import QApplication
import sys
from Panel_Administrador import panel_administrador
from Login import Login
if __name__ == "__main__":
app = QApplication(sys.argv)
p = panel_administrador()
l = Login()
l.btn.clicked.connect(p.show)
p.btn.clicked.connect(l.show)
p.show()
sys.exit(app.exec())