Tốt nhất là để xác định một mô hình tùy chỉnh (QAbstractTableModel
lớp con). Bạn có thể muốn có một số QSqlQueryModel
làm thành viên trong lớp tùy chỉnh này.
Nếu đó là một mô hình read-only, bạn cần phải thực hiện ít nhất là những phương pháp:
int rowCount(const QModelIndex &parent) const;
int columnCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const;
và cho các mô hình cũng cư xử cũng
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
Nếu bạn cần mô hình để có thể chỉnh sửa/gửi dữ liệu, mọi thứ có liên quan nhiều hơn một chút và bạn cũng sẽ cần phải triển khai các phương pháp sau:
Qt::ItemFlags flags(const QModelIndex &index) const;
bool setData(const QModelIndex &index, const QVariant &value, int role=Qt::EditRole);
bool insertRows(int position, int rows, const QModelIndex &index=QModelIndex());
bool removeRows(int position, int rows, const QModelIndex &index=QModelIndex());
Điều gì thực sự sẽ thay đổi một diện mạo hàng nằm trong giá trị trả về của phương pháp này:
QVariant data(const QModelIndex &index, int role) const;
Một ví dụ câm:
QVariant MyCustomModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
int row = index.row();
int col = index.column();
switch (role)
{
case Qt::BackgroundRole:
{
if(somecondition){
// background for this row,col is blue
return QVariant(QBrush (QColor(Qt::blue)));
}
// otherwise background is white
return QVariant(QBrush (QColor(Qt::white)));
}
case Qt::DisplayRole:
{
// return actual content for row,col here, ie. text, numbers
}
case Qt::TextAlignmentRole:
{
if (1==col)
return QVariant (Qt::AlignVCenter | Qt::AlignLeft);
if (2==col)
return QVariant (Qt::AlignVCenter | Qt::AlignTrailing);
return QVariant (Qt::AlignVCenter | Qt::AlignHCenter);
}
}
}
+1 để tham khảo giải pháp với đại biểu. Tôi đã quên điều đó. – dschulz
tôi cần phải thiết lập một màu cho mỗi giá trị của một colmun bảng (tên SELECT, tình trạng TỪ người dùng) trong trường hợp "tình trạng" này, bạn có thể chỉnh sửa mã này. – Tineo
optionV4-> backgroundBrush = QBrush (calculateColorForRow (index.row())); nó tạo ra lỗi – Tineo