4

PyQt5系列教程(二十二)表格中添加按钮

 1 year ago
source link: https://xugaoxiang.com/2022/03/21/pyqt5-22-add-button-to-table/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

软硬件环境

  • Windows 10 64bit
  • Anaconda3 with python 3.7
  • PyQt5

进入 designer 设计界面,非常简单,拖控件,一个 Label 和 一个 Table Widget

b21150a0adb1cade.png

然后双击表格处,添加表格的列元素,分别是 编号数量操作数量 部分使用些模拟数据,操作 列,我们就来添加一个 清零 按钮,作用就是将第二列的元素清零

5436aae5010f2221.png

操作完成后保存成 .ui 文件,然后转换成对应的 python 代码

pyuic5.bat -o ui.py project.ui

最后写核心代码

import sys
import random

from PyQt5.QtWidgets import QMainWindow, QTableWidgetItem, QAbstractItemView, QPushButton, QApplication, QWidget, QHBoxLayout

from ui import Ui_MainWindow

class MainWindow(QMainWindow, Ui_MainWindow):

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)

        # 设置总的行数,列数已经在designer中做好了
        self.tableWidget.setRowCount(5)
        self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)

        for i in range(5):
            # 设置第一列
            item_id = QTableWidgetItem(str(i + 1))
            self.tableWidget.setItem(i, 0, item_id)

            # 设置第二列
            item_num = QTableWidgetItem(str(random.randint(10, 100)))
            self.tableWidget.setItem(i, 1, item_num)

            # 设置第三列,也就是添加一个清零按钮
            self.tableWidget.setCellWidget(i, 2, self.add_button(i, 1))

    def add_button(self, row, column):

        # 实例化按钮
        self.button_add = QPushButton('清零')
        # 设置样式
        self.button_add.setStyleSheet(''' text-align : center;
                                            background-color : Red;
                                            height : 30px;
                                            font : 12px; ''')
        # 绑定槽函数                                    
        self.button_add.clicked.connect(lambda: self.clear_number(row, column))

        # 将按钮放在一个水平布局里
        widget = QWidget()
        layout = QHBoxLayout()
        layout.addWidget(self.button_add)
        widget.setLayout(layout)
        return widget

    def clear_number(self, row, column):
        item = QTableWidgetItem('0')
        self.tableWidget.setItem(row, column, item)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    windows = MainWindow()
    windows.show()
    sys.exit(app.exec_())

程序启动后,点击相应行中的清零按钮,那么同行中的数量值就变为了0

fd7404b375d5ffb1.png

https://github.com/xugaoxiang/learningPyQt5

PyQt5系列教程

更多PyQt5教程,请移步

https://xugaoxiang.com/category/python/pyqt5/


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK