PyQt5: Example of combined use of LineEdit and PushButton

Hello everyone, I'm Jiaojiao, a rookie programming for big guys. I am writing a small form analysis tool recently. There are 2 LineEdits on the main interface, that is, single-line input box controls, which allow users to enter the form path.

Now there are 3 cases:

  • Type 1: If the user does not input or the content is empty, the button behind will display a gray icon.

  • Type 2: The user enters, but the path is wrong, and the button behind will display a red icon.

  • Type 3: If the user input is correct, the button behind will display a green icon.

As shown below:

The key code is as follows:

# 设置按钮图标
self.pushButton.setIcon(QIcon('./images/输入正确.png'))
# 设置按钮图标大小(这个也可以在Qt Designer中提前设置好)
self.pushButton.setIconSize(QSize(25, 25))

The complete code is as follows:

    self.lineEdit.textChanged.connect(self.path_check_ld1)
    self.lineEdit_2.textChanged.connect(self.path_check_ld2)

def path_check_ld1(self, text):
    if text:
        try:
            df_1 = pd.read_excel(f'{text}')
            self.pushButton.setIcon(QIcon('./images/表单完成2.png'))
        except:
            self.pushButton.setIcon(QIcon('./images/删除文件.png'))

    else:
        self.pushButton.setIcon(QIcon('./images/等待文件.png'))


def path_check_ld2(self, text):
    if text:
        try:
            df_1 = pd.read_excel(f'{text}')
            self.pushButton_2.setIcon(QIcon('./images/表单完成2.png'))
        except:
            self.pushButton_2.setIcon(QIcon('./images/删除文件.png'))

    else:
        self.pushButton_2.setIcon(QIcon('./images/等待文件.png'))

Supplementary note:

  • The try statement for handling exceptions in Python is used here. There are two commonly used styles:

  • try: possible exception code, except: exception handling method, else: no exception handling method

  • try: may be abnormal code, finally: run right or wrong

  • It can be seen that the above two custom functions have text parameters, because the textChanged() signal of LineEdit will return the text content in LineEdit. Just because I didn't know this feature, I took a lot of detours in the code that was originally very simple.

Special thanks:

Finally, I am very grateful to the nickname in the group for the big guy who hates me . It was this little brother who helped me solve it. It is useless to talk too much, there is only one sentence: a good person lives a safe life!

Guess you like

Origin blog.csdn.net/weixin_53989417/article/details/129019757