buttondelegate.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include "buttondelegate.h"
  2. #include <QStyledItemDelegate>
  3. #include <qDebug>
  4. ButtonDelegate::ButtonDelegate(int buttonColumn,QObject *parent) : QStyledItemDelegate(parent),buttonColumn(buttonColumn){
  5. // 构造函数实现(如果需要)
  6. }
  7. void ButtonDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
  8. if (index.column() == buttonColumn) {
  9. QStyleOptionButton buttonOption1;
  10. QStyleOptionButton buttonOption2;
  11. QRect rect = option.rect;
  12. rect.adjust(0, 0, -1, -1); // 调整大小以适应边框
  13. // 第一个按钮
  14. buttonOption1.rect = rect.adjusted(0, 0, -rect.width() / 2, 0);
  15. buttonOption1.text = "删除"; // 按钮文本
  16. buttonOption1.state = QStyle::State_Enabled;
  17. QApplication::style()->drawControl(QStyle::CE_PushButton, &buttonOption1, painter);
  18. // 第二个按钮
  19. buttonOption2.rect = rect.adjusted(rect.width() / 2, 0, 0, 0);
  20. buttonOption2.text = "编辑"; // 按钮文本
  21. buttonOption2.state = QStyle::State_Enabled;
  22. QApplication::style()->drawControl(QStyle::CE_PushButton, &buttonOption2, painter);
  23. } else {
  24. QStyledItemDelegate::paint(painter, option, index);
  25. }
  26. }
  27. bool ButtonDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) {
  28. if (index.column() == buttonColumn && event->type() == QEvent::MouseButtonPress) {
  29. QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
  30. QRect rect = option.rect;
  31. rect.adjust(0, 0, -1, -1); // 调整大小以适应边框
  32. // 检测第一个按钮的点击
  33. QRect button1Rect = rect.adjusted(0, 0, -rect.width() / 2, 0);
  34. if (button1Rect.contains(mouseEvent->pos())) {
  35. handleButtonClick (index.row(),1); // 处理第一个按钮点击
  36. return true;
  37. }
  38. // 检测第二个按钮的点击
  39. QRect button2Rect = rect.adjusted(rect.width() / 2, 0, 0, 0);
  40. if (button2Rect.contains(mouseEvent->pos())) {
  41. handleButtonClick(index.row(), 2); // 处理第二个按钮点击
  42. return true;
  43. }
  44. }
  45. return QStyledItemDelegate::editorEvent(event, model, option, index);
  46. }
  47. void ButtonDelegate::handleButtonClick(int row,int button) {
  48. // qDebug() << "行号: " << row << ", 按钮: " << button;
  49. emit buttonClicked(row, button); // 发射信号
  50. }