1.添加数据
void Reader::AddTableView(QTableView* tv, QMap<QString, QString> mData)
{
QStandardItemModel* model = new QStandardItemModel();
model->setColumnCount(2);
model->setHeaderData(0, Qt::Horizontal, QString::fromLocal8Bit("Addr"));
model->setHeaderData(1, Qt::Horizontal, QString::fromLocal8Bit("Value"));
model->setRowCount(mData.size());
for (int i = 0; i < mData.size(); i++)
{
model->setHeaderData(i, Qt::Vertical, i + 1);
}
QMap<QString, QString>::iterator it = mData.begin();
for (int i = 0; it != mData.end(); it++, i++)
{
model->setItem(i, 0, new QStandardItem(it.key()));
model->setItem(i, 1, new QStandardItem(it.value()));
}
tv->setModel(model);
}
2.设置背景颜色
QModelIndex jcIndex = tv->model()->index(i, j);
tv->model()->setData(jcIndex, QBrush(Qt::red), Qt::BackgroundRole);
3.禁止编辑
//tableview整体禁止编辑
tv->setEditTriggers(QAbstractItemView::NoEditTriggers);
4.自定义编辑
#pragma once
#include <QItemDelegate>
#include <QWidget>
class QTableReadOnlyDelegate : public QItemDelegate
{
//委托
public:
QTableReadOnlyDelegate(QWidget* parent = NULL) : QItemDelegate(parent)
{
}
QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option,
const QModelIndex& index) const override //final
{
Q_UNUSED(parent)
Q_UNUSED(option)
Q_UNUSED(index)
return NULL;
}
};
#include "QTableViewTest.h"
#include "qtablereadonlydelegate.h"
#include <qstandarditemmodel.h>
QTableViewTest::QTableViewTest(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
MemberInit();
WidgetInit();
}
void QTableViewTest::MemberInit()
{
}
void QTableViewTest::WidgetInit()
{
QTableReadOnlyDelegate* tableDelegate = new QTableReadOnlyDelegate();
ui.tableView->setItemDelegateForColumn(0, tableDelegate);
ui.tableView->setItemDelegateForRow(0, tableDelegate);
QStandardItemModel* model = new QStandardItemModel();
model->setColumnCount(2);
model->setHeaderData(0, Qt::Horizontal, QString::fromLocal8Bit("Addr"));
model->setHeaderData(1, Qt::Horizontal, QString::fromLocal8Bit("Value"));
QMap<QString, QString> mData;
mData.insert("0x11", "66");
mData.insert("0x22", "77");
model->setRowCount(mData.size());
for (int i = 0; i < mData.size(); i++)
{
model->setHeaderData(i, Qt::Vertical, i + 1);
}
QMap<QString, QString>::iterator it = mData.begin();
for (int i = 0; it != mData.end(); it++, i++)
{
model->setItem(i, 0, new QStandardItem(it.key()));
model->setItem(i, 1, new QStandardItem(it.value()));
}
ui.tableView->setModel(model);
}
|