Как я могу сделать нажатие кнопки автоматически (изначально, сразу), когда экран всплывает? - PullRequest
0 голосов
/ 29 января 2019

Я пишу код для создания настольного приложения.Я хочу сделать клик Refresh button автоматически при всплывающем окне для обновления старых записей. Но я почему-то не могу этого сделать.

Я написал код для обновления меток, но это не сработало,После этого я попытался вызвать self.refresh_record() между __init__ методом, который также выполняет обновление метки, но затем он подвергается бесконечной рекурсии.

class ClassMainWindow(QMainWindow, MainWindow.Ui_MainWindow):
    """Welcome to the class of MainWindow (obviously) ?"""

    def __init__(self):
        """Constructor with no legacy of parameter"""

        # noinspection PyArgumentList
        QMainWindow.__init__(self)
        self.setupUi(self)
        self.showMaximized()

        """
        # for updating date label right on MainWindow
        self.lbl_date.setText("Date: " + str(datetime.now().date()) + "\n     (YYYY-MM-DD)")
        self.lbl_date.setFont(QFont('Arial', 15))  # we have to update a label's font after doing explicit modification on it

        self.lbl_buy.setText("Buy: " + str(Entry.total_buy_method()))
        self.lbl_buy.setFont(QFont('Arial', 15))

        self.lbl_sell.setText("Sell: " + str(Entry.total_sell_method()))
        self.lbl_sell.setFont(QFont('Arial', 15))
        """

        # declaration of all instance variables
        self.add_record_dialog_object = ClassAddRecordDialog()
        self.self_object = None   # instance variable for showing window again with fresh content
        self.delete_record_dialog_object = ClassDeleteRecordDialog()
        self.graph_dialog = Window()

        # calls of event handlers
        self.btn_add_record.clicked.connect(self.pop_up_add_record_dialog)
        self.btn_refresh.clicked.connect(self.refresh_record)
        self.btn_delete_record.clicked.connect(self.pop_up_delete_record_dialog)
        self.btn_statistics.clicked.connect(self.pop_up_statistics_dialog)

        # assigned shortcuts to some reputed actions which has high frequency of usage
        self.shortcut1 = QtWidgets.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_R), self)
        # noinspection PyUnresolvedReferences
        self.shortcut1.activated.connect(self.refresh_record)

        self.shortcut2 = QtWidgets.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_A), self)
        # noinspection PyUnresolvedReferences
        self.shortcut2.activated.connect(self.pop_up_add_record_dialog)

        self.shortcut3 = QtWidgets.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_D), self)
        # noinspection PyUnresolvedReferences
        self.shortcut3.activated.connect(self.pop_up_delete_record_dialog)

        self.shortcut4 = QtWidgets.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_S), self)
        # noinspection PyUnresolvedReferences
        self.shortcut4.activated.connect(self.pop_up_statistics_dialog)

        # to count number of rows in Data.csv file in order to write it in tabular form
        with open("Data.csv", "r") as file_of_main2:
            file_reader = csv.reader(file_of_main2, delimiter=",")
            rows = len(list(file_reader)) - 1

        # to set number of rows and columns of table
        self.tbl_widget_existing_records.setRowCount(rows)
        self.tbl_widget_existing_records.setColumnCount(7)

        # to set specific column width of table widget (column_index, size)
        self.tbl_widget_existing_records.setColumnWidth(0, 70)
        self.tbl_widget_existing_records.setColumnWidth(1, 60)
        self.tbl_widget_existing_records.setColumnWidth(3, 60)  # third column (index2) is by default well-settled
        self.tbl_widget_existing_records.setColumnWidth(4, 85)
        self.tbl_widget_existing_records.setColumnWidth(5, 85)
        self.tbl_widget_existing_records.setColumnWidth(6, 600)

        # these are self-explanatory statements ?
        file_of_data = pd.read_csv("Data.csv")
        dict_index_to_headers = {0: "Date", 1: "Type", 2: "Product", 3: "Quantity", 4: "Price_Per_Unit",
                                 5: "Total_Price", 6: "Description"}

        # to assign column name to @table
        self.tbl_widget_existing_records.setHorizontalHeaderLabels(["Date", "Type", "Product Name", "Quantity",
                                                                    "Price per Unit", "Total Price", "Description"])

        # when we want to write content from file to table...
        for i in range(rows):
            for j in dict_index_to_headers:
                self.value = str(file_of_data.at[i, dict_index_to_headers[j]])
                self.tbl_widget_existing_records.setItem(i, j, QTableWidgetItem(self.value))

    # definitions of event handlers
    def refresh_record(self):
        """In order to re-load fresh data of MainWindow into table"""

        self.close()
        self.self_object = ClassMainWindow()    # specified ClassName here because I'm afraid of MaximumRecursiveError ?
        self.self_object.retranslateUi(self.self_object)

        self.self_object.showMaximized()

        # for updating date label right on MainWindow
        self.self_object.lbl_date.setText("Date: " + str(datetime.now().date()) + "\n     (YYYY-MM-DD)")
        self.self_object.lbl_date.setFont(QFont('Arial', 15))  # we have to update a label's font after doing explicit modification on it

        self.self_object.lbl_buy.setText("Buy: " + str(Entry.total_buy_method()))
        self.self_object.lbl_buy.setFont(QFont('Arial', 15))

        self.self_object.lbl_sell.setText("Sell: " + str(Entry.total_sell_method()))
        self.self_object.lbl_sell.setFont(QFont('Arial', 15))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...