开发者

indexWidget() unexpectedly returns a NULL pointer

开发者 https://www.devze.com 2023-01-27 05:51 出处:网络
I am attempting to create a model/view application in Qt 4.7.1.I am a very new Qt developer. Summary of what I am attempting to do:

I am attempting to create a model/view application in Qt 4.7.1. I am a very new Qt developer.

Summary of what I am attempting to do:

I have a treeview that is organized as a rectangular table of rows and columns. One column of items contains a button. By default this button is to be transparent and disabled. A given button is to become visible and enabled when the mouse is hovering over its row.

The approach I am pursuing is to

  1. find the model index for the cell that the mouse is hovering over, and
  2. obtain a pointer to the widget associated with the widget, and
  3. using this pointer manipulate the visibility of the button within said widget.

I cannot get a valid pointer to the widget.

my current code looks like this:

void HistoryTreeView::mouseMoveEvent(QMouseEvent *event)
{
   QAbstractItemModel *m(model());

   // Only do something when a model is set.
   if (m)
   {
      QModelIndex index = indexAt(even开发者_运维百科t->pos());
      if (index.isValid())
      {
         // if the mouse has moved to another row
         if (index.row() != m_currentRow)
         {
           m_currentRow = index.row();

           QMessageBox::information( this, "HistoryTreeView", QString("index(%1)").arg(index.row()));

           QWidget * item = indexWidget(index);
           Q_ASSERT(item != NULL  );
        }
     }
     else  // model is invalid
     {
         m_currentRow = -1;
     }
  }

  QTreeView::mouseMoveEvent(event);
}

The symptoms:

I expected the call to indexWidget() to return a valid pointer to the widget the mouse is over. Instead it unexpectedly returns a NULL pointer.

Commentary:

The variable named 'index' is acting as I expected because the QMessageBox shows the correct row value. Consequently I do not think there is anything wrong with the value I am providing to indexWidget().

This is just debug code. It is missing things like code that selects the column that holds the buttons.


OK, Here is the nature of my error as I understand it.

I had incorrectly understood that every item in a view is its own widget. I now understand that the view itself is a widget, but that individual items within the view are not widgets, per se.

Because I had misunderstood that view items were widgets I believed that could:

  1. obtain an index from a given element in a model,
  2. use indexWidget() to obtain a Widget * to the view item associated with the model element
  3. and then use this pointer to manipulate the view item as though it was a widget.

indexWidget() simply returned a NULL because view items are not widgets.

0

精彩评论

暂无评论...
验证码 换一张
取 消