Qt開發:列表QTableView列添加Button

在列表裏面添加任何其他組件,比如Button,一般都需要繼承delegate,然後繼承後重繪,但是這樣過於複雜,這裏有一個簡單的方法,理論上可以擴展到任何組件

以單個window裏面添加到表格爲例
代碼
mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

class MainWindow : public QMainWindow
{
    Q_OBJECT

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

private slots:
    void onTableBtnClicked();

};

#endif // MAINWINDOW_H

mainwindow.cpp

#include <QTableView>
#include <QHeaderView>
#include <QStandardItemModel>
#include <QStringList>
#include <QString>
#include <QPushButton>
#include <QDebug>
#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    setFixedSize(700, 500);

    // add tableview
    QTableView *tableView = new QTableView(this);
    tableView->setMinimumSize(700, 500);
    tableView->verticalHeader()->hide(); // hide row number

    QStandardItemModel *tableModel = new QStandardItemModel(this);
    tableView->setModel(tableModel); // recommend to set model before detail settings

    // set columns
    QStringList columnTitles;
    columnTitles << "id" << "name" << "status" << "action";
    tableModel->setHorizontalHeaderLabels(columnTitles);
//    tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); // column fit the contents

    // add contents
    for(int i = 0; i < 7; i++)
    {
        tableModel->setItem(i, 0, new QStandardItem(QString::number(i + 1)));
        tableModel->setItem(i, 1, new QStandardItem(QString("hello qt tablview %1").arg(i)));
        tableModel->setItem(i, 2, new QStandardItem("normal"));

        // add button to the last column
        QPushButton *button = new QPushButton("Start");

        // set custom property
        button->setProperty("id", i); // set custom property
        button->setProperty("name", QString("hello qt tablview %1").arg(i));
        button->setProperty("status", "normal");

        // set click event
        connect(button, SIGNAL(clicked()), this, SLOT(onTableBtnClicked()));

        // notice every time insert the button at the last line
        tableView->setIndexWidget(tableModel->index(tableModel->rowCount() - 1, 3), button);
    }
}

void MainWindow::onTableBtnClicked()
{
    QPushButton *button = (QPushButton *)sender();
    qDebug() << button->property("id").toInt() << endl;
    qDebug() << button->property("name").toString() << endl;
    qDebug() << button->property("status").toString() << endl;
}

MainWindow::~MainWindow()
{

}

截圖
在這裏插入圖片描述

思路

  • 使用QTableView的setIndexWidget函數添加額外的組件,需要指定好索引
  • 在Button上設置好自定義的屬性,綁定信號槽後,在點擊事件的響應中將屬性值傳出
  • 注意在設置Button時確保QTableView已經設置過model了

Tip

  • 如非必要,Qt中運用表格之類的複雜組件,用widget而不是view來做會輕鬆很多
  • 實際上田間button在Qt中用QTableWidget來實現更簡單,只需要tableWidget->setCellWidget(row, col, pBtn),並可以擴展到其他組件
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章