首页 > 其他分享 >Qt之QTableWidget的使用

Qt之QTableWidget的使用

时间:2023-04-13 14:23:51浏览次数:31  
标签:Qt QTableWidget list json background 使用 table btn check

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QtWidgets>
#include <QDebug>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonValue>
#include <QJsonDocument>

#define TABLE_HEADER_STYLE  "QHeaderView::section {border-top: 1px solid #d8d8d8; border-bottom: 1px solid #d8d8d8; border-right: 1px solid #d8d8d8; background: #f6f7f9; color: #333333; font-size: 16px;}"

#define HSCROLL_BAR_STYLE   "QScrollBar {background: transparent; height: 10px; margin: 0px;}" \
                            "QScrollBar::handle {background: #dfdfe1; border-radius: 3px; margin: 0px;}" \
                            "QScrollBar::handle:hover {background: lightgray;}" \
                            "QScrollBar::handle:pressed {background: #dfdfe1;}" \
                            "QScrollBar::sub-page {background: transparent;}" \
                            "QScrollBar::add-page {background: transparent;}" \
                            "QScrollBar::sub-line {background: transparent; width: 0px;}" \
                            "QScrollBar::add-line {background: transparent; width: 0px;}"

#define VSCROLL_BAR_STYLE   "QScrollBar {background: transparent; width: 10px; margin: 0px;}" \
                            "QScrollBar::handle {background: #dfdfe1; border-radius: 3px; margin: 0px;}" \
                            "QScrollBar::handle:hover {background: lightgray;}" \
                            "QScrollBar::handle:pressed {background: #dfdfe1;}" \
                            "QScrollBar::sub-page {background: transparent;}" \
                            "QScrollBar::add-page {background: transparent;}" \
                            "QScrollBar::sub-line {background: transparent; height: 0px;}" \
                            "QScrollBar::add-line {background: transparent; height: 0px;}"

class MainWindow : public QWidget
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void table_check_clicked();
    void table_item_check_clicked();
    void buy_button_clicked();
    void on_btn_load_data_clicked();
    void on_btn_delete_data_clicked();
    void solt_cell_entered(int row, int column);

private:
    QPushButton *m_btn_load_data;
    QPushButton *m_btn_delete_data;

    QTableWidget *m_table_list;
    QCheckBox *m_table_check;

    QByteArray m_json_data;
};
#endif // MAINWINDOW_H
#include "main_window.h"

MainWindow::MainWindow(QWidget *parent)
    : QWidget(parent)
{
    this->setFixedSize(800,  500);

    m_btn_load_data = new QPushButton("加载", this);
    connect(m_btn_load_data, &QPushButton::clicked, this, &MainWindow::on_btn_load_data_clicked);
    m_btn_load_data->setGeometry(24, 10, 100, 30);

    m_btn_delete_data = new QPushButton("删除", this);
    connect(m_btn_delete_data, &QPushButton::clicked, this, &MainWindow::on_btn_delete_data_clicked);
    m_btn_delete_data->setGeometry(130, 10, 100, 30);

    m_table_list = new QTableWidget(0, 7, this);
    m_table_list->setStyleSheet("QTableWidget {color: #333333; font-size: 16px;}");
    m_table_list->horizontalHeader()->setStyleSheet(TABLE_HEADER_STYLE);
    m_table_list->horizontalScrollBar()->setStyleSheet(HSCROLL_BAR_STYLE);
    m_table_list->verticalScrollBar()->setStyleSheet(VSCROLL_BAR_STYLE);


    m_table_list->setGeometry(24, 70, 750, 400);
    m_table_list->horizontalHeader()->setFixedHeight(36);
    m_table_list->verticalHeader()->setFixedWidth(36);
    m_table_list->setSelectionMode(QAbstractItemView::NoSelection);
    m_table_list->setEditTriggers(QAbstractItemView::NoEditTriggers);
    m_table_list->setFocusPolicy(Qt::NoFocus);
    m_table_list->setFrameShape(QFrame::NoFrame);
    m_table_list->setMouseTracking(true);
    connect(m_table_list, &QTableWidget::cellEntered, this, &MainWindow::solt_cell_entered);

    m_table_list->verticalHeader()->hide();
    m_table_list->horizontalHeader()->setSectionsClickable(false);
    m_table_list->horizontalHeader()->setStretchLastSection(true);
    m_table_list->setColumnWidth(0, 36);
    m_table_list->setColumnWidth(1, 60);
    m_table_list->setColumnWidth(2, 120);
    m_table_list->setColumnWidth(3, 120);
    m_table_list->setColumnWidth(4, 120);
    m_table_list->setColumnWidth(5, 120);
    m_table_list->setColumnWidth(6, 120);
    m_table_list->setColumnWidth(7, 100);

    QWidget *fix_line = new QWidget(m_table_list);
    fix_line->setStyleSheet("QWidget {border: 1px solid #d8d8d8;}");
    fix_line->setGeometry(0, 0, 1, 36);

    QStringList column_name_list;
    column_name_list << "" << "序号" << "游戏" << "游戏价格" << "游戏类型" << "备注" << "操作";
    m_table_list->setHorizontalHeaderLabels(column_name_list);

    m_table_check = new QCheckBox(m_table_list);
    connect(m_table_check, SIGNAL(clicked()), this, SLOT(table_check_clicked()));
    m_table_check->setGeometry(10, 10, 16, 16);

    QJsonArray json_array;

    QJsonObject json_object1;
    json_object1.insert("game", "刺客信条起源");
    json_object1.insert("price", "298元");
    json_object1.insert("type", "PVE");
    json_object1.insert("remarks", "开放世界");
    json_array.append(json_object1);

    QJsonObject json_object2;
    json_object2.insert("game", "刺客信条奥德赛");
    json_object2.insert("price", "298元");
    json_object2.insert("type", "PVE");
    json_object2.insert("remarks", "开放世界");
    json_array.append(json_object2);

    QJsonObject json_object3;
    json_object3.insert("game", "只狼:影逝二度");
    json_object3.insert("price", "268元");
    json_object3.insert("type", "PVE");
    json_object3.insert("remarks", "魂类");
    json_array.append(json_object3);

    QJsonObject json_object4;
    json_object4.insert("game", "英雄联盟");
    json_object4.insert("price", "免费");
    json_object4.insert("type", "PVP");
    json_object4.insert("remarks", "MOBA");
    json_array.append(json_object4);

    QJsonObject json;
    json.insert("game_list", QJsonValue(json_array));

    m_json_data = QJsonDocument(json).toJson(QJsonDocument::Compact);
}

MainWindow::~MainWindow()
{
}

void MainWindow::table_check_clicked()
{
    QCheckBox *check = static_cast<QCheckBox *>(sender());
    int state = check->checkState();

    for (int i = 0; i < m_table_list->rowCount(); i++) {
        QCheckBox *temp = (QCheckBox *)m_table_list->cellWidget(i, 0);
        if (state == Qt::Checked) {
            temp->setCheckState(Qt::Checked);
        } else {
            temp->setCheckState(Qt::Unchecked);
        }
    }
}

void MainWindow::table_item_check_clicked()
{
    QCheckBox *check = static_cast<QCheckBox *>(sender());
    int state = check->checkState();

    if (state == Qt::Unchecked) {
        m_table_check->setCheckState(Qt::Unchecked);
    } else {
        for (int i = 0; i < m_table_list->rowCount(); i++) {
            QCheckBox *temp = (QCheckBox *)m_table_list->cellWidget(i, 0);
            if (temp->checkState() == Qt::Unchecked) {
                return;
            }
        }
        m_table_check->setCheckState(Qt::Checked);
    }
}

void MainWindow::buy_button_clicked()
{
    QPushButton *btn_buy = static_cast<QPushButton *>(sender()) ;
    int row = btn_buy->property("row").toInt();
    QString game = m_table_list->item(row, 2)->text();
    QString price = m_table_list->item(row, 3)->text();
    QString type = m_table_list->item(row, 4)->text();
    QString remarks = m_table_list->item(row, 5)->text();

    qDebug() << "game:" << game << "price:" << price << "type:" << type << "remarks:" << remarks;
}

void MainWindow::on_btn_load_data_clicked()
{
    QJsonParseError json_parse;
    QJsonDocument json_doucment = QJsonDocument::fromJson(m_json_data, &json_parse);
    if (json_parse.error == QJsonParseError::NoError) {
        if (json_doucment.isObject()) {
            QJsonObject json_object = json_doucment.object();
            qDebug() << "json_object:" << json_object;

            QJsonArray json_array = json_object.take("game_list").toArray();
            m_table_check->setCheckState(Qt::Unchecked);

            for (int i = 0; i < m_table_list->rowCount(); i++) {
                m_table_list->setRowHidden(i, false);
            }

            m_table_list->clearContents();
            m_table_list->setRowCount(json_array.size());

            for (int i = 0; i < json_array.size(); i++) {
                QJsonObject mac_obj = json_array[i].toObject();
                QString game = mac_obj.take("game").toString();
                QString price = mac_obj.take("price").toString();
                QString type = mac_obj.take("type").toString();
                QString remarks = mac_obj.take("remarks").toString();

                /* 复选框 */
                QCheckBox *check = new QCheckBox;
                connect(check, SIGNAL(clicked()), this, SLOT(table_item_check_clicked()));
                check->setStyleSheet("QCheckBox {padding-top: 10px; padding-left: 10px;}");
                check->setFixedSize(26, 26);
                check->setProperty("row", i);
                m_table_list->setCellWidget(i, 0, check);

                /* 表格内容 */
                m_table_list->setItem(i, 1, new QTableWidgetItem(QString::number(i + 1)));
                m_table_list->setItem(i, 2, new QTableWidgetItem(game));
                m_table_list->setItem(i, 3, new QTableWidgetItem(price));
                m_table_list->setItem(i, 4, new QTableWidgetItem(type));
                m_table_list->setItem(i, 5, new QTableWidgetItem(remarks));

                for (int j = 1; j <= 5; j++) {
                    m_table_list->item(i, j)->setTextAlignment(Qt::AlignCenter);
                }

                /* 操作栏 */
                QWidget *widget_op = new QWidget;
                QHBoxLayout *layout_op = new QHBoxLayout;
                layout_op->setAlignment(Qt::AlignCenter);
                layout_op->setSpacing(5);
                layout_op->setSpacing(0);
                layout_op->setMargin(0);

                QPushButton *btn_op = new QPushButton("购买");
                connect(btn_op, SIGNAL(clicked()), this, SLOT(buy_button_clicked()));
                btn_op->setStyleSheet("QPushButton {border: 1px solid #067EFF; border-radius: 4px; padding-top: -3px; background-color: #ffffff; color: #067EFF; font-size: 16px;}"
                                      "QPushButton:hover {background-color: #067EFF; color: #ffffff;}"
                                      "QPushButton:pressed {background-color: #ffffff; color: #067EFF;}");
                btn_op->setFixedSize(55, 25);
                btn_op->setProperty("row", i);

                layout_op->addWidget(btn_op);
                widget_op->setLayout(layout_op);
                m_table_list->setCellWidget(i, 6, widget_op);
            }
        }
    }
}

void MainWindow::on_btn_delete_data_clicked()
{
    for (int i = 0; i < m_table_list->rowCount(); i++) {
        QCheckBox *temp = (QCheckBox *)m_table_list->cellWidget(i, 0);
        if (temp->checkState() == Qt::Checked) {
            int row = temp->property("row").toInt();
            QString game = m_table_list->item(row, 2)->text();
            QString price = m_table_list->item(row, 3)->text();
            QString type = m_table_list->item(row, 4)->text();
            QString remarks = m_table_list->item(row, 5)->text();

            qDebug() << "game:" << game << "price:" << price << "type:" << type << "remarks:" << remarks;
        }
    }
}

void MainWindow::solt_cell_entered(int row, int column)
{
    if (column != 2) {
        return;
    }

    QTableWidgetItem *item = m_table_list->item(row, column);
    if (item == NULL) {
        return;
    }
    QToolTip::showText(QCursor::pos(), item->text());

}

结果如下:

 

标签:Qt,QTableWidget,list,json,background,使用,table,btn,check
From: https://www.cnblogs.com/QingYiShouJiuRen/p/17314643.html

相关文章

  • 使用云净装win10系统
    一、准备工作:1制作pe启动U盘。2下载windowsiso镜像。3设置装系统电脑U盘启动。二、安装系统:1插入U盘,重启电脑。2进入PE系统。3安装系统,等待重启。 1制作pe启动U盘。需要一个8GB以上的U盘,正常运行的系统并下载云净装机。云净装机,使用百度搜索下就有了,......
  • .NetCore(.NET6)中使用swagger和swagger版本控制
    原文:.NetCore(.NET6)中使用swagger和swagger版本控制目录一、.NET6中使用swagger二、.NET6中使用swagger版本控制 回到顶部一、.NET6中使用swagger swagger支持API自动生成同步的在线文档,下面在.NET6中引入1.建.NET6应用并建以下控制器///<summary>///......
  • C#中使用自动化测试代码
    转载自:https://blog.csdn.net/yangyong1250/article/details/128892399......
  • h5使用高德获取用户当前位置信息
    在index.html文件中引入高德js文件:key需要从高德获取获取key<scripttype="text/javascript"src="https://webapi.amap.com/maps?v=1.4.15&key=f77da011880c2d55aeccba6446b85c78"></script>js文件我将方法写入了单独的js文件:locationService.jsimportAMapfr......
  • k8s1.27.x 最新版本使用kubeadm 的containerd的方式安装
    标签(空格分隔):kubernetes系列一:k8s1.27.x的概述1.1:k8s1.27.x更新Kubernetesv1.27正式发布,这是2023年的第一个版本!此版本包含60个增强功能。其中18个增强功能进入Alpha阶段,29个进入Beta阶段,13个进入Stable阶段。版本主题和标志Kubernetesv1.27:ChillVibes......
  • 升级win10后无法使用IE浏览器??
     控制面板搜索选项    ......
  • JAVA使用OpenOffice文件转换
    下载jar包maven中央仓库包不支持docx文件所以不建议使用。jar包是为了方便链接下载链接:https://nchc.dl.sourceforge.net/project/jodconverter/JODConverter/2.2.2/jodconverter-2.2.2.zip 解压后找到:jodconverter-2.2.2\jodconverter-2.2.2\lib\jodconverter-2.2.2.jar放......
  • uniapp 使用vconsole
    1、安装vconsolenpminstallvconsole2、引用vconsole,找到main.js文件中,加上以下代码(区分环境):if(process.env.H_NODE_ENV!=='production'){ constvconsole=require('vconsole') Vue.prototype.$vconsole=newvconsole()}3、效果: ......
  • 使用go modules目录构成
    首先在workspace工作空间gocode下面生成一个go.work文件,使用命令:goworkinit./a工程./b工程,这里面要列出所有的工程go.work文件内容:go1.20use(./src/chapter12./src/chapter13./src/chapter14./src/chapter15)然后再每个工程下面生成一个go.mod......
  • 使用反三角函数来计算两个矩形框中心点之间的夹角
    首先,求出两个矩形框中心点的横纵坐标差,再使用反三角函数(如反正切函数)求出夹角的弧度数。最后,将弧度数转换为角度数。如果点(x,y)落在第一、第二象限,则返回的角度值为负数;如果点落在第三象限,则返回的角度值为正数;如果点落在第四象限,则返回的角度值为正数或负数,具体取决于y和x......