#include
class CheckView: public QListView
{
public:
CheckView(QWidget* parent = 0): QListView(parent)
{
}
bool eventFilter(QObject* object, QEvent* event)
{
if (event->type() == QEvent::MouseButtonRelease)
{
QMouseEvent* mouse = static_cast(event);
QModelIndex index = indexAt(mouse->pos());
if (index.isValid())
{
// check if the mouse was released over the checkbox
QStyleOptionButton option;
option.QStyleOption::operator=(viewOptions());
option.rect = visualRect(index);
QRect rect = style()->subElementRect(QStyle::SE_ViewItemCheckIndicator, &option);
if (rect.contains(mouse->pos()))
{
// mouse was release over a checkbox
// bypass combobox and deliver the event just for the listview
QListView::mouseReleaseEvent(mouse);
return true;
}
}
}
return false;
}
};
class CheckModel: public QStandardItemModel
{
public:
CheckModel(QObject* parent = 0): QStandardItemModel(parent)
{
// a must
insertColumn(0);
}
Qt::ItemFlags flags(const QModelIndex& index) const
{
return QStandardItemModel::flags(index) | Qt::ItemIsUserCheckable;
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QComboBox* combo = new QComboBox;
CheckModel* model = new CheckModel(combo);
CheckView* view = new CheckView(combo);
combo->setModel(model);
combo->setView(view);
// these 2 lines below are important and must be
// applied AFTER QComboBox::setView() because
// QComboBox installs it's own filter on the view
view->installEventFilter(view); // <--- !!!
view->viewport()->installEventFilter(view); // <--- !!!
for (int i = 0; i < 5; ++i)
{
combo->addItem(QString::number(i));
// init check state for every added item!
combo->setItemData(i, Qt::Unchecked, Qt::CheckStateRole);
}
combo->show();
return a.exec();
}
阅读(1161) | 评论(0) | 转发(0) |