2016-05-02 25 views
0

我想要實現以下功能:我有一個MySQL表,我通過QSqlRelationalTableModel連接到該表。我想要最後一列從數據庫中獲取布爾值,並查看連接到動作的按鈕,具體取決於布爾值的值。我創建的模型和視圖(tableModelMySqlTableModel,這是一個public QSqlRelationalTableModel):Qt - 如何連接QSqlRelationalDelegate中創建的按鈕

tableView = new QTableView(this); 
tableView->setModel(tableModel); 
tableView->setItemDelegate(new tableDelegate(this)); 

我的問題是,我怎麼這些按鈕連接到TableModel中的作用?

委託看起來像這樣,生成相應的按鈕:

void tableDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { 

    if (index.column() != 4) { 
     QSqlRelationalDelegate::paint(painter, option, index); 
    } else if (index.model()->data(index).toInt() == 1){ 
     QStyleOptionButton button; 
     QRect r = option.rect;//getting the rect of the cell 
     int x,y,w,h; 
     x = r.left() + r.width() - 90;//the X coordinate 
     y = r.top();//the Y coordinate 
     w = 90;//button width 
     h = 30;//button height 
     button.rect = QRect(x,y,w,h); 
     button.text = "Logout"; 
     button.state = QStyle::State_Enabled; 

     QApplication::style()->drawControl(QStyle::CE_PushButton, &button, painter); 
    } else { 
     QStyleOptionButton button; 
     QRect r = option.rect;//getting the rect of the cell 
     int x,y,w,h; 
     x = r.left() + r.width() - 90;//the X coordinate 
     y = r.top();//the Y coordinate 
     w = 90;//button width 
     h = 30;//button height 
     button.rect = QRect(x,y,w,h); 
     button.text = "Login"; 
     button.state = QStyle::State_Enabled; 


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

所以,我想每個按鈕button連接到分別tableModel.login()tableModel.logout()。我怎樣才能做到這一點?

回答

0

沒有按鈕。您可以繪製按鈕,但實際上該按鈕不存在。這只是單元格內部按鈕的「圖片」。

你可以做的是通過調用QAbstractItemView::setIndexWidget()方法插入真正按鈕到表或到QAbstractItemView::clicked()信號連接到您的插槽。

如果你決定這樣做,第二種方法是,如果你想讓它看起來像一個真正的按鈕,你必須在按下時用QStyle::State_Sunken繪製僞按鈕。

+0

哪個對象應該調用setIndexWidget方法? –

+0

這並不重要。假設管理* tableView *的對象。 – Tomas

+0

如果我用'setIndexWidget()'來做,我點擊一個按鈕就會消失。這是它應該如何? –