buttondelegate.cpp 2.5 KB

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