2012-04-18 4 views
6
void MyWindow::initializeModelBySQL(QSqlQueryModel *model,QTableView *table,QString sql){ 
     model = new QSqlQueryModel(this); 
     model->setQuery(sql); 
} 

이 방법을 사용하여 QSQlQueryModels를 QTableviews로 설정할 수 있습니다.QTableView 행에 색상을 설정하십시오.

하지만 어떻게 셀 값을 기반으로 행에 색상을 설정할 수 있습니까?

답변

18

보기는 셀의 Qt::BackgroundRole 역할에 따라 백그라운드를 그리는 실제로 행 모양을 변경 될지 0이 메소드의 리턴 값에 놓여값은 해당 역할에 대해 QAbstractItemModel::data(index, role)입니다.

당신은 당신의 계산 된 색을 반환 data()을 재정의 QSqlQueryModel을 하위 클래스, 또는 Qt는> 4.8이 있다면, 당신은 QIdentityProxyModel 사용할 수 있습니다

class MyModel : public QIdentityProxyModel 
{ 
    QColor calculateColorForRow(int row) const { 
     ... 
    } 

    QVariant data(const QModelIndex &index, int role) 
    { 
     if (role == Qt::BackgroundRole) { 
      int row = index.row(); 
      QColor color = calculateColorForRow(row);   
      return QBrush(color); 
     } 
     return QIdentityProxyModel::data(index, role); 
    } 
}; 

을 그리고 SQL로,보기에이 모델을 사용 모델은 소스로 QIdentityProxyModel::setSourceModel으로 설정됩니다. 당신은 QAbstractItemView::setItemDelegate으로보기에 설정 대리자로 변경 모델을 유지하고 배경을 수정할 수 있습니다

또는

:

class BackgroundColorDelegate : public QStyledItemDelegate { 

public: 
    BackgroundColorDelegate(QObject *parent = 0) 
     : QStyledItemDelegate(parent) 
    { 
    } 
    QColor calculateColorForRow(int row) const; 

    void initStyleOption(QStyleOptionViewItem *option, 
         const QModelIndex &index) const 
    { 
     QStyledItemDelegate::initStyleOption(option, index); 

     QStyleOptionViewItemV4 *optionV4 = 
       qstyleoption_cast<QStyleOptionViewItemV4*>(option); 

     optionV4->backgroundBrush = QBrush(calculateColorForRow(index.row())); 
    } 
}; 

를 마지막 방법은 C++ 코드에서 번역하는 것이 명확하지 않다으로, 다음은 파이썬에서 이에 상응하는 내용입니다.

def initStyleOption(self, option, index): 
    super(BackgroundColorDelegate,self).initStyleOption(option, index) 
    option.backgroundBrush = calculateColorForRow(index.row()) 
+1

+1 (대리인이있는 솔루션 참조). 나는 그것을 잊었다. – dschulz

+0

"colmun"(SELECT name, status FROM users) 테이블의 각 값에 대한 색상을 설정해야합니다.이 경우 "status"이 코드를 편집 할 수 있습니까? – Tineo

+0

optionV4-> backgroundBrush = QBrush (calculateColorForRow (index.row())); 그것은 오류를 생성합니다 – Tineo

3

가장 좋은 방법은 사용자 지정 모델 (QAbstractTableModel 하위 클래스)을 정의하는 것입니다. 이 사용자 정의 클래스의 구성원으로 QSqlQueryModel을 원할 수도 있습니다.

int rowCount(const QModelIndex &parent) const; 
int columnCount(const QModelIndex &parent) const; 
QVariant data(const QModelIndex &index, int role) const; 

하고 모델이 필요하면 바르게 행동 모델도

QVariant headerData(int section, Qt::Orientation orientation, int role) const; 

할 수 있도록 : 그것은 읽기 전용 모델의 경우

, 당신은 적어도 이러한 방법을 구현해야 데이터를 수정/제출하려면 일들이 좀 더 복잡해 지므로 다음 방법을 구현해야합니다.

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()); 
QVariant data(const QModelIndex &index, int role) const; 

벙어리 예 :

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); 

     } 
    } 

    } 
관련 문제