'PyQt5: GUI crashes when I attempt to filter

I'm relatively new to PyQt5, so it may be a simple mistake, but here is my problem.

So my goal is to have a GUI where you can select filters and input data into these filters. Then click a "search" button and have a new window pop up with your filtered results.

The pop up window works perfectly fine when the dataframe has no filters applied, but as soon as I try to filter the dataframe, my GUI will crash after pressing "search".

Here is my code, the issue is in the "search_clicked" function. If you have any solutions or suggestions it would be extremely helpful.

I found out that it was because df was written before the class. After moving it to the init method and making it self.df, the code works fine

import sys
import csv
import pandas as pd
import numpy as np
from PyQt5 import QtCore, QtGui
from PyQt5.QtCore import QAbstractTableModel, QSortFilterProxyModel, Qt
from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import (
    QApplication,
    QWidget,
    QPushButton,
    QRadioButton,
    QHBoxLayout,
    QVBoxLayout,
    QLabel,
    QLineEdit,
    QListWidget,
    QButtonGroup,
    QTableView,
    QGroupBox,
    QDialog
    )
def data_parser():
    df = pd.read_csv("cleaned_crime_data.csv")
    df.drop(["Unnamed: 0"], inplace = True, axis = 1)
    return df

df = data_parser()

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()  
        self.setWindowTitle("Crime Search")
        #hbox0 & hbox1
        self.v_button = QRadioButton("Violent")
        self.nv_button = QRadioButton("Not Violent")
        self.both_button = QRadioButton("Both")
        self.filter_label = QLabel("Filter/s:")
        self.date_button = QPushButton("Date")
        self.day_button = QPushButton("Week Day")
        self.month_button = QPushButton("Month")
        self.year_button = QPushButton("Year")
        self.time_button = QPushButton("Time of Day")
        self.neighborhood_button = QPushButton("Neighborhood")
        self.data_label = QLabel("Data:")
        self.results = QTableView()
        self.search = QPushButton("Search")
        self.date_box = QLineEdit("2010-05-25")
        self.day_box = QLineEdit("Friday")
        self.month_box = QLineEdit("May")
        self.year_box = QLineEdit("2010")
        self.time_box = QLineEdit("Afternoon")
        self.neighborhood_box = QLineEdit("Georgia Tech")

        self.model = pandasModel(df)
        self.results.setModel(self.model)

        proxyModel = QSortFilterProxyModel(self)
        proxyModel.setSourceModel(self.model)
        self.results.setModel(proxyModel)
        
        groupBox = QGroupBox()

        groupBoxLayout = QVBoxLayout()
        groupBox.setLayout(groupBoxLayout)
        groupBoxLayout.addWidget(self.v_button)
        groupBoxLayout.addWidget(self.nv_button)
        groupBoxLayout.addWidget(self.both_button)


        self.search.setFont(QFont("",25))
        self.search.setAutoDefault(True)
        self.both_button.setChecked(True)

        self.date_box.setEnabled(False)
        self.day_box.setEnabled(False)
        self.month_box.setEnabled(False)
        self.year_box.setEnabled(False)
        self.time_box.setEnabled(False)
        self.neighborhood_box.setEnabled(False)

        self.date_button.pressed.connect(self.date_clicked)
        self.day_button.pressed.connect(self.day_clicked)
        self.month_button.pressed.connect(self.month_clicked)
        self.year_button.pressed.connect(self.year_clicked)
        self.time_button.pressed.connect(self.time_clicked)
        self.neighborhood_button.pressed.connect(self.neighborhood_clicked)

        self.search.pressed.connect(self.search_clicked)


        ###Layout####
        hbox0 = QHBoxLayout()
        hbox0.addWidget(self.filter_label)
        # hbox0.addWidget(self.v_button)
        # hbox0.addWidget(self.nv_button)
        # hbox0.addWidget(self.both_button)
        #hbox0.addWidget(groupBox)
        
        hbox1 = QHBoxLayout()
        hbox1.addWidget(self.date_button)
        hbox1.addWidget(self.day_button)
        hbox1.addWidget(self.month_button)
        hbox1.addWidget(self.year_button)
        hbox1.addWidget(self.time_button)
        hbox1.addWidget(self.neighborhood_button)
        hbox1.addWidget(groupBox)
        # hbox1.addWidget(self.v_button)
        # hbox1.addWidget(self.nv_button)
        # hbox1.addWidget(self.both_button)

        hbox2 = QHBoxLayout()
        hbox2.addWidget(self.date_box)
        hbox2.addWidget(self.day_box)
        hbox2.addWidget(self.month_box)
        hbox2.addWidget(self.year_box)
        hbox2.addWidget(self.time_box)
        hbox2.addWidget(self.neighborhood_box)
        hbox2.addWidget(self.search)

        hbox3 = QHBoxLayout()
        hbox3.addWidget(self.data_label)
        # hbox3.addWidget(self.search)

        vbox1 = QVBoxLayout()
        vbox1.addWidget(self.results)
        
        vbox_main = QVBoxLayout()
        
        vbox_main.addLayout(hbox0)
        vbox_main.addLayout(hbox1)
        vbox_main.addLayout(hbox2)
        vbox_main.addLayout(hbox3)
        vbox_main.addLayout(vbox1)
        self.setLayout(vbox_main)

    ###Fucntions###
    def date_clicked(self):
        if self.date_box.isEnabled():
            self.date_box.setEnabled(False)
        else:
            self.date_box.setEnabled(True)
    def day_clicked(self):
        if self.day_box.isEnabled():
            self.day_box.setEnabled(False)
        else:
            self.day_box.setEnabled(True)
    def month_clicked(self):
        if self.month_box.isEnabled():
            self.month_box.setEnabled(False)
        else:
            self.month_box.setEnabled(True)
    def year_clicked(self):
        if self.year_box.isEnabled():
            self.year_box.setEnabled(False)
        else:
            self.year_box.setEnabled(True)
    def time_clicked(self):
        if self.time_box.isEnabled():
            self.time_box.setEnabled(False)
        else:
            self.time_box.setEnabled(True)
    def neighborhood_clicked(self):
        if self.neighborhood_box.isEnabled():
            self.neighborhood_box.setEnabled(False)
        else:
            self.neighborhood_box.setEnabled(True)

    def search_clicked(self):
    
        ##This is the part that won't work##

        # if self.date_box.isEnabled():
        #   df = df.mask((df["Occur Date"] == self.date_box.text)).dropna()
        # if self.day_box.isEnabled():
        #   df = df.mask((df["Day Occured"] == self.day_box.text)).dropna()
        # if self.month_box.isEnabled():
        #   df = df.mask((df["Month Occured"] == self.month_box.text)).dropna()
        # if self.year_box.isEnabled():
        #   df = df.mask((df["Year Occured"] == self.year_box.text)).dropna()
        # if self.time_box.isEnabled():
        #   df = df.mask((df["Time of Day"] == self.month_box.text)).dropna()
        # if self.neighborhood_box.isEnabled():
        #   df = df.mask((df["Neighborhood"] == self.neighborhood_box.text)).dropna()
        # if self.v_button.isChecked():
        #   df = df.mask((df["Violent"] == False )).dropna()
        # if self.nv_button.isChecked():
        #   df = df.mask((df["Violent"] == True )).dropna()


        self.launchPopup(df)

    def launchPopup(self, dataframe):
        pop = Popup(dataframe, self)
        pop.show()


### Popup Window ###
class Popup(QDialog):
    def __init__(self, dataframe, parent):
        super().__init__(parent)
        #self.setModal(True)
        self.resize(950, 500)
        self.view = QTableView()
        self.view.setModel(pandasModel(dataframe))

        vbox = QVBoxLayout()
        vbox.addWidget(self.view)
        self.setLayout(vbox)


### Pandas DataFrame ###
class pandasModel(QAbstractTableModel):

    def __init__(self, data):
        QAbstractTableModel.__init__(self)
        self._data = data

    def rowCount(self, parent=None):
        return self._data.shape[0]

    def columnCount(self, parnet=None):
        return self._data.shape[1]

    def data(self, index, role=Qt.DisplayRole):
        if index.isValid():
            if role == Qt.DisplayRole:
                return str(self._data.iloc[index.row(), index.column()])
        return None

    def headerData(self, col, orientation, role):
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            return self._data.columns[col]
        return None
        

        




if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = MainWindow()
    main.show()
    sys.exit(app.exec_())
    results.resize(800, 600)
    results.show()



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source