PDA

View Full Version : QTableView HOVERING ISSUE



kiran p
31st May 2011, 08:25
Hi all,
I am trying to implement hovering on QTableview i subclassed QStyledItemDelegate and reimplemented paint as show in the below code
i am not able to get hovering properly for the total row
the same code is working fine with QTreeview.


void Delegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
if (!index.isValid())
{
return; //early exit
}

const QTableView* const view = dynamic_cast< QTableView* >(this->parent());
Q_ASSERT (NULL != view);
if (NULL == view)
{
return; //another early exit
}

int width = 0;
for (int colIndex = 0; colIndex < TOTAL_COLUMNS; colIndex++)
{
if (!view->isColumnHidden(colIndex))
{
width += view->columnWidth(colIndex);
}
}

const QRect rowRect = option.rect.united(QRect(0, option.rect.top(), width, option.rect.height()));

if (option.state & QStyle::State_Selected)
{
painter->fillRect(option.rect, QColor(110, 161, 241));
}

if(option.state & QStyle::State_MouseOver)
{
painter->fillRect(rowRect ,QColor(191, 205, 228));
}


QString dispText;
QRect textRect = option.rect.adjusted(4, 3, 0, 0);
QString text = displayText( index.data(), view ? view->locale() : QLocale() );

switch(index.column())
{
case COL_1:
{

dispText = option.fontMetrics.elidedText(text, Qt::ElideRight, textRect.width());
painter->drawText(textRect, Qt::AlignAbsolute, tr("%1 ").arg(dispText));

}
break;
case COL_2:
{
}

Santosh Reddy
2nd June 2011, 06:24
Kiran, Please use Code tags to post code, it is very difficult to read the code.

So, you say it is working for QTreeView, and does not work for QTableView, Did you try debugging it, what happens when you hover the mouse, is State_MouseOver option event received?


for (int colIndex = 0; colIndex < TOTAL_COLUMNS; colIndex++)
can be better written as

for (int colIndex = 0; colIndex < view->model()->columnCount(); colIndex++)

joyer83
2nd June 2011, 07:45
Do understand that the delegate is used to draw each item in the view. In QTableView one item is same as one cell. When the view paints itself it draws those items from top to bottom, and left to right. With your implementation you are painting the mouse over effect outside the rectangle that current item occupies. When next item in the row is painted it will paint itself over the mouseover effect. Maybe this the reason?

I think you should check the mouseover status by manually instead of trusting the style option's state information as it is valid only for the current item/cell.

Maybe something like this:


QPoint mousePosition = view->mapFromGlobal( QCursor::pos() );
if( rowRect.contains( mousePosition ) ) // check if mouse cursor is on top of current row
{
// paint mouseover effect only for current item
painter->fillRect(option.rect, QColor(191, 205, 228));
}