Trouble updating QTableWidget - python

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.

Related

How to open content of a file in MDI subwindow from treeview

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

Get current value of another widget in a custom (promoted) widget in Qt Designer using PyQt5

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

Python pyqt5 Reminder and Notepad Launcher

I have met with a problem on Python. I tried to create a Reminder and Notepad.There is no troubles with Reminder, but the notepad is quite hard. I use QPlainTextEdit to open .txt files, save notes and so on.The problem is that it does not work. You may start looking from the class fileeki, cause notepad starts there. My interface is written in QTdesigner and the file's type is ui. I use mainwindow which is convertod to .py from .ui , but other widgets are as usual in .ui .Please help me!!!
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5 import uic
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QRadioButton, QVBoxLayout, QStatusBar
from PyQt5.QtWidgets import QLabel, QPushButton, QMessageBox, QFileDialog, QPlainTextEdit
from PyQt5.QtGui import QPixmap
from ui_filebir import Ui_MainWindow
from win10toast import ToastNotifier
import time
import sqlite3
import easygui
from tkinter import filedialog
from tkinter import *
class MyWidget(QMainWindow,Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.resize(520, 300)
self.pushButton.clicked.connect(self.notepad_run)
self.re_but.clicked.connect(self.reminder_run)
self.pushButton_2.clicked.connect(self.dbrun)
self.rate = self.lineEdit.text()
def dbrun(self):
pass
#con = sql.connect('dbrate.db')
#cur = con.cursor()
#cur.execute(query)
#res = cur.execute(query)
#con.commit()
#con.close()
def notepad_run(self):
self.uineweki = fileeki()
self.uineweki.show()
self.close()
def reminder_run(self):
self.ui_fileush = fileush()
self.ui_fileush.show()
self.close()
class fileeki(QWidget):
def __init__(self, *args, **kwargs):
super().__init__()
uic.loadUi('uineweki.ui', self)
self.editor = QPlainTextEdit()
self.path = None
self.pushButton.clicked.connect(self.opening_run)
self.pushButton_2.clicked.connect(self.saving_run)
self.pushButton_3.clicked.connect(self.saveac)
self.pushButton_4.clicked.connect(self.bak)
def dialog_critical(self, s):
dlg = QMessageBox(self)
dlg.setText(s)
dlg.setIcon(QMessageBox.Critical)
dlg.show()
def opening_run(self):
path, _ = QFileDialog.getOpenFileName(self, "Open file", "", "Text documents (*.txt);All files (*.*)")
if path:
try:
with open(path, 'rU') as f:
text = f.read()
except Exception as e:
self.dialog_critical(str(e))
else:
self.path = path
self.editor.setPlainText(text)
def saving_run(self):
if self.path is None:
return self.saveac()
self._save_to_path(self.path)
def saveac(self):
path = QFileDialog.getSaveFileName(self, "Save file", "", "Text documents (*.txt);All files (*.*)")
if not path:
return
self._save_to_path(self.path)
def _save_to_path(self, path):
text = self.editor.toPlainText()
try:
with open(path, 'w') as f:
f.write(text)
except Exception as e:
self.dialog_critical(str(e))
else:
self.path = path
self.update_title()
def new_run(self):
pass
def bak(self):
self.close()
self.nazad = MyWidget()
self.nazad.show()
class fileush(QWidget):
def __init__(self, *args):
super().__init__()
uic.loadUi('ui_fileush.ui', self)
self.pushButton.clicked.connect(self.running)
self.pushButton_2.clicked.connect(self.bakk)
def running(self):
toaster = ToastNotifier()
self.first_input = self.lineEdit.text()
self.second_input = self.lineEdit_2.text()
t = time.sleep(int(self.first_input))
toaster.show_toast(self.second_input)
def bakk(self):
self.close()
self.nazad = MyWidget()
self.nazad.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyWidget()
ex.show()
sys.exit(app.exec())
my github https://github.com/iMAGA07/yandexProj
You are trying to set the text to the new QPlainTextEdit you created, but you should actually point it to the one you use in the gui:
def opening_run(self):
# ...
else:
self.path = path
# change this
# self.editor.setPlainText(text)
# to this
self.plainTextEdit.setPlainText(text)
That self.plainTextEdit is the object you created in designer (the object names are listed in the object inspector tree). Obviously, this also means that you don't need to create self.editor in the first place.

Indexing PyQt5 combobox when using QFileSystemModel

I need to select the default file that appears in a combobox from a directory listing of files. With a normal combobox, it is easy enough to find the index of the value you want using .findText, but this does not appear to work for QFileSystemModel comboboxes, possibly due to the way the list of options does not populate until the directory listing can be resourced.
Here is what I have tried:
import sys
import collections
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget, QComboBox
from PyQt5.QtCore import QSize, QRect
class ComboWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.setMinimumSize(QSize(640, 140))
self.setWindowTitle("Combobox example")
centralWidget = QWidget(self)
self.setCentralWidget(centralWidget)
# Create combobox and add items.
self.fsm = QtWidgets.QFileSystemModel()
self.fsm.setNameFilters(["*.txt"])
self.configComboBox = QtWidgets.QComboBox(self)
self.configComboBox.setGeometry(QRect(40, 40, 491, 31))
self.configComboBox.setObjectName(("comboBox"))
self.configComboBox.setModel(self.fsm)
self.fsm.setFilter(QtCore.QDir.NoDotAndDotDot | QtCore.QDir.Files)
# "text_files" is a subdir of current dir with files
# example1.txt, example2.txt, example3.txt
self.configComboBox.setRootModelIndex(self.fsm.setRootPath("text_files"))
# V V This section does not work V V
index = self.configComboBox.findText(MainConfig.settings["default_txt_file"])
self.configComboBox.setCurrentIndex(index)
class MainConfig:
settings = collections.OrderedDict()
#staticmethod
def createDefaultConfig(name):
MainConfig.settings["default_txt_file"] = "example3.txt"
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWin = ComboWindow()
mainWin.show()
sys.exit( app.exec_() )
As I indicated in this answer, the QFileSystemModel is loaded asynchronously in a new thread so you must use the directoryLoaded signal to know when the information is finished loading:
import collections
import os
import sys
from PyQt5.QtWidgets import (
QApplication,
QComboBox,
QFileSystemModel,
QMainWindow,
QWidget,
)
from PyQt5.QtCore import pyqtSlot, QDir, QRect, QSize
class ComboWindow(QMainWindow):
def __init__(self, parent=None):
super(ComboWindow, self).__init__(parent=None)
self.setMinimumSize(QSize(640, 140))
self.setWindowTitle("Combobox example")
centralWidget = QWidget(self)
self.setCentralWidget(centralWidget)
# Create combobox and add items.
self.fsm = QFileSystemModel()
self.fsm.setNameFilters(["*.txt"])
self.configComboBox = QComboBox(self)
self.configComboBox.setGeometry(QRect(40, 40, 491, 31))
self.configComboBox.setObjectName(("comboBox"))
self.configComboBox.setModel(self.fsm)
self.fsm.setFilter(QDir.NoDotAndDotDot | QDir.Files)
self.fsm.directoryLoaded.connect(self.on_directoryLoaded)
current_dir = os.path.dirname(os.path.realpath(__file__))
dir_path = os.path.join(current_dir, "text_files")
self.configComboBox.setRootModelIndex(self.fsm.setRootPath(dir_path))
#pyqtSlot(str)
def on_directoryLoaded(self, path):
index = self.configComboBox.findText(MainConfig.settings["default_txt_file"])
self.configComboBox.setCurrentIndex(index)
class MainConfig:
settings = collections.OrderedDict()
#staticmethod
def createDefaultConfig(name):
MainConfig.settings["default_txt_file"] = name
if __name__ == "__main__":
MainConfig.createDefaultConfig("example3.txt")
app = QApplication(sys.argv)
mainWin = ComboWindow()
mainWin.show()
sys.exit(app.exec_())

calling a list instance from another class

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

Categories

Resources