2014-04-04 38 views
1

我目前正试图通过继承QTableView中建立一个QT表,QAbstractTableModel和QStyledItemDelegate到maintian MVC archiectecture的一些外表。QT QTableView中实现切换按钮,复选框代表

我使用这个简单的例子为基地的基础上,因为我没有去Qt的表类近前:

http://qt-project.org/doc/qt-4.8/modelview.html

反正表主要是文本列,但它也需要一个单个切换按钮列和单个复选框列。

我注意到,该模型的数据的方法,可以用来实现一个复选框,但我会需要一个自定义委托的按钮,所以我打算用它的复选框也。

反正我是无法找到创建使用QTableView中的对象与文本,复选框和按钮的混合物表在互联网上的任何像样的例子。你们中的任何一位好先生能指点我的方向吗?

+0

我已经说过上面我创建的委托。提供一些示例或新的线程或不回答。创建一个委托并重写单元格内容是给定的。否则,我会使用默认的代理。使用按钮或复选框执行操作的示例是必需的。 – kh25

+0

所以你想让我们为你写一个代码?没有任何企图从你身边? –

+1

使用相同的代码,但画一个按钮,而不是复选框:http://stackoverflow.com/a/16301316/1035613 –

回答

1

基于上述梅德我已经实现了所提供的信息在我的委托中绘制我的按钮和复选框的绘画方法。显然这需要一个editorEvent()来做任何事情,如果证明它有用,我也可以添加它。

void DDUTableDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, 
          const QModelIndex& index) const 
{ 
int col = index.column(); 

if (col == VIEW_COLUMN) { 
    // Draw our checkbox indicator 
    bool value = index.data(Qt::EditRole).toBool(); 
    QStyleOptionButton checkbox_indicator; 

    // Set our button state to enabled 
    checkbox_indicator.state |= QStyle::State_Enabled; 
    checkbox_indicator.state |= (value) ? QStyle::State_On : QStyle::State_Off; 

    // Get our deimensions 
    checkbox_indicator.rect = QApplication::style()->subElementRect(QStyle::SE_CheckBoxIndicator, &checkbox_indicator, NULL); 

    // Position our indicator 
    const int x = option.rect.center().x() - checkbox_indicator.rect.width()/2; 
    const int y = option.rect.center().y() - checkbox_indicator.rect.height()/2; 

    checkbox_indicator.rect.moveTo(x, y); 

    if (option.state & QStyle::State_Selected) { 
     painter->fillRect(option.rect, option.palette.highlight());  
    } 

    QApplication::style()->drawControl(QStyle::CE_CheckBox, &checkbox_indicator, painter); 
} 
else if (col == TEST_COLUMN) { 
    bool value = index.data(Qt::EditRole).toBool(); 

    QStyleOptionButton button; 

    // Set our button to fill the entire cell contents 
    button.rect = option.rect; 

    // Set our button state to enabled 
    button.state |= QStyle::State_Enabled; 

    if (value) { 
     button.state |= QStyle::State_Sunken; 
     button.text = STOP_TEST; 
    } 
    else { 
      button.text = START_TEST; 
    } 

    if (option.state & QStyle::State_Selected) { 
     painter->fillRect(option.rect, option.palette.highlight());   
    } 

    QApplication::style()->drawControl(QStyle::CE_PushButton, &button, painter); 

} 
} 
2

你不需要自定义委托具有复选框,并在你的tableview切换按钮。你可以简单地让您的项目可检查并设置它为模型,如:

QStandardItem *item = new QStandardItem(true); 
item->setCheckable(true); 
item->setCheckState(Qt::Unchecked); 

QStandardItemModel * model = new QStandardItemModel(0, 2); 
model->setRowCount(1); 
model->setItem(0, 0, item); 

对于一个切换按钮,你可以这样做:

QPushButton * but = new QPushButton(this); 
but->setCheckable(true); 
but->setText("Toggle"); 

ui->tableView->setIndexWidget(model->item(0,1)->index(),but);