clickabletableview.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include "clickabletableview.h"
  2. ClickableTableView::ClickableTableView(QWidget *parent)
  3. : QTableView(parent) {
  4. // 构造函数的实现
  5. // // 设置背景颜色
  6. // QPalette palette = this->palette();
  7. // palette.setColor(QPalette::Base, Qt::white);
  8. // palette.setColor(QPalette::AlternateBase, Qt::lightGray);
  9. // palette.setColor(QPalette::Highlight, QColor(0, 120, 215));
  10. // palette.setColor(QPalette::HighlightedText, Qt::white);
  11. // this->setPalette(palette);
  12. // // 设置网格线颜色
  13. // this->setGridStyle(Qt::SolidLine);
  14. // QColor gridColor(Qt::darkGray);
  15. this->setStyleSheet(QString("QTableView { selection-background-color: blue;}"
  16. "QTableView QTableCornerButton::section { background: transparent; } "
  17. "QHeaderView::section { background-color: gray; color: white; padding-left: 4px; padding-right: 4px; } "));
  18. // // 设置边框
  19. // this->setFrameShape(QFrame::Box);
  20. // this->setLineWidth(1);
  21. // // 设置单元格内边距
  22. // this->verticalHeader()->setDefaultSectionSize(30);
  23. // this->horizontalHeader()->setDefaultSectionSize(100);
  24. // }
  25. }
  26. void ClickableTableView::mouseReleaseEvent(QMouseEvent *event) {
  27. QModelIndex index = indexAt(event->pos());
  28. if (index.isValid() && index.column() == 8) {
  29. QRect rect = visualRect(index);
  30. QRect firstButtonRect = rect.adjusted(0, 0, -rect.width() / 2, 0);
  31. QRect secondButtonRect = rect.adjusted(rect.width() / 2, 0, 0, 0);
  32. if (firstButtonRect.contains(event->pos())) {
  33. // 处理第一个按钮点击事件
  34. qDebug() << "Button 1 clicked at row:" << index.row();
  35. displayRowData(index.row());
  36. } else if (secondButtonRect.contains(event->pos())) {
  37. // 处理第二个按钮点击事件
  38. qDebug() << "Button 2 clicked at row:" << index.row();
  39. displayRowData(index.row());
  40. }
  41. }
  42. QTableView::mouseReleaseEvent(event);
  43. }
  44. void ClickableTableView::displayRowData(int row) {
  45. QAbstractItemModel* model = this->model();
  46. if (model) {
  47. QString rowData;
  48. for (int col = 0; col < model->columnCount(); ++col) {
  49. QModelIndex index = model->index(row, col);
  50. QVariant data = model->data(index);
  51. rowData += QString("Column %1: %2 | ").arg(col).arg(data.toString());
  52. }
  53. qDebug() << "Row" << row << "Data:" << rowData;
  54. }
  55. }