我在Sqlite数据库中有一个表格,我使用QTableview和QSqlQueryModel来显示它。第一列需要有一个复选框作为标题,而且该列中的所有项目都需要是复选框。我已经将第一列标题实现为复选框,并且它的功能非常完美。
由于该列中的复选框需要居中显示,因此我使用了一个委托来绘制它。 我已经使用以下代码绘制复选框,但是它们无法选中或取消选中。我不知道如何实现这个功能。
以下代码展示了我使用QSqlQueryModel和QTableView从数据库加载表格的方法。
由于该列中的复选框需要居中显示,因此我使用了一个委托来绘制它。 我已经使用以下代码绘制复选框,但是它们无法选中或取消选中。我不知道如何实现这个功能。
static QRect CheckBoxRect(const QStyleOptionViewItem &view_item_style_options) {
QStyleOptionButton check_box_style_option;
QRect check_box_rect = QApplication::style()->subElementRect(
QStyle::SE_CheckBoxIndicator,
&check_box_style_option);
QPoint check_box_point(view_item_style_options.rect.x() +
view_item_style_options.rect.width() / 2 -
check_box_rect.width() / 2,
view_item_style_options.rect.y() +
view_item_style_options.rect.height() / 2 -
check_box_rect.height() / 2);
return QRect(check_box_point, check_box_rect.size());
}
CheckBoxDelegate::CheckBoxDelegate(QObject *parent) :
QStyledItemDelegate(parent)
{
}
void CheckBoxDelegate::paint(QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index) const {
bool checked = index.model()->data(index, Qt::DisplayRole).toBool();
QStyleOptionButton check_box_style_option;
check_box_style_option.state |= QStyle::State_Enabled;
if (checked) {
check_box_style_option.state |= QStyle::State_On;
} else {
check_box_style_option.state |= QStyle::State_Off;
}
check_box_style_option.rect = CheckBoxRect(option);
QApplication::style()->drawControl(QStyle::CE_CheckBox,
&check_box_style_option,
painter);
}
以下代码展示了我使用QSqlQueryModel和QTableView从数据库加载表格的方法。
//Load the tableview with the database table
QSqlQueryModel model = new QSqlQueryModel();
//Initializaton of the query
QSqlQuery *query = new QSqlQuery(dbm->db);
query->prepare("SELECT * FROM UserData");
if(query->exec())
{
model->setQuery(*query);
ui->tableView->setModel(model);
//The header delegate to paint a checkbox on the header
HeaderDelegate *myHeader = new HeaderDelegate(Qt::Horizontal, ui->tableView);
ui->tableView->setHorizontalHeader(myHeader);
int RowCount = model->rowCount();
qDebug() << RowCount;
CheckBoxDelegate *myCheckBoxDelegate = new CheckBoxDelegate();
ui->tableView->setItemDelegateForColumn(0,myCheckBoxDelegate);
ui->tableView->horizontalHeader()->setClickable(true);
ui->tableView->setSortingEnabled(true);
}
请问您如何处理这个问题?非常感谢您的帮助。
setIndexWidget
声明:该函数仅应用于在与数据项对应的可见区域内显示静态内容。如果您想要显示自定义动态内容或实现自定义编辑器小部件,则应继承QItemDelegate
子类。还应注意,这会破坏模型/视图模式,因此最好使用自定义的QItemDelegate
子类。 - Folling