【问题标题】:How to locate the row number of my button in QTableview in Qt如何在 Qt 的 QTableview 中找到我的按钮的行号
【发布时间】:2018-04-27 20:23:25
【问题描述】:

我有一个函数可以将 QStyleOptionButton 添加到 QTableview 中的某个列, 我希望能够在单击时获取每个按钮的行号并将值存储在变量中。

这是我的代码 delegate.cpp

MyDelegate::MyDelegate(QObject *parent)
     : QItemDelegate(parent)
 {

 }


 void MyDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
 {
     QStyleOptionButton button;
     QRect r = option.rect;//getting the rect of the cell
     int x,y,w,h;
     x = r.left() + r.width() - 30;//the X coordinate
     y = r.top();//the Y coordinate
     w = 30;//button width
     h = 30;//button height
     button.rect = QRect(x,y,w,h);
     button.text = "View log";
     button.state = QStyle::State_Enabled;

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

 bool MyDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
 {
     if( event->type() == QEvent::MouseButtonRelease )
     {
         QMouseEvent * e = (QMouseEvent *)event;
         int clickX = e->x();
         int clickY = e->y();

         QRect r = option.rect;//getting the rect of the cell
         int x,y,w,h;
         x = r.left() + r.width() - 30;//the X coordinate
         y = r.top();//the Y coordinate
         w = 30;//button width
         h = 30;//button height

         if( clickX > x && clickX < x + w )
             if( clickY > y && clickY < y + h )
             {
                // int row=tableview->rowAt(pos.y());
                 // int column=tableview->columnAt(pos.x());

                 QDialog * d = new QDialog();
                 d->setGeometry(0,0,100,100);
                // QTextBrowser *txt = new QTextBrowser(row, column);
                 d->show();
             }
     }

     return true;
 }

【问题讨论】:

    标签: c++ qt qt5 qtableview qitemdelegate


    【解决方案1】:

    你必须使用 QModelIndex:

    bool MyDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
    {
        Q_UNUSED(model)
        if( event->type() == QEvent::MouseButtonRelease )
        {
            QMouseEvent * e = (QMouseEvent *)event;
            QPoint p = e->pos();
    
            QRect r = option.rect;//getting the rect of the cell
            QRect re(r.topRight() - QPoint(30, 0), QSize(30, 30));
    
            if(re.contains(p)){
                int row = index.row(); // <---- row
                int column = index.column(); // <---- column
    
                QDialog * d = new QDialog();
                d->setGeometry(0,0,100,100);
                d->show();
             }
        }
        return true;
    }
    

    【讨论】:

      猜你喜欢
      • 2011-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-06
      • 1970-01-01
      相关资源
      最近更新 更多