You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

111 rivejä
2.8 KiB

  1. #include "button.h"
  2. #include <QPainter>
  3. #include <QStyleOptionGraphicsItem>
  4. #include <QMenu>
  5. #include <QFileDialog>
  6. Button::Button(const QString &type) : Item(type)
  7. {
  8. }
  9. QRectF Button::boundingRect() const
  10. {
  11. return QRectF(0, 0, 50, 50);
  12. }
  13. void Button::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *)
  14. {
  15. painter->setRenderHint(QPainter::Antialiasing);
  16. if (type_ == "按钮") {
  17. if (!imagePath_.isEmpty() && !customPixmap_.isNull())
  18. {
  19. painter->drawPixmap(0,0,50,50,customPixmap_);
  20. }
  21. else{
  22. painter->drawRect(0,0,50,50);
  23. }
  24. }
  25. if (!registerId_.isEmpty()) {
  26. painter->save();
  27. painter->setFont(QFont("Arial", 8));
  28. painter->setPen(Qt::red);
  29. QString text;
  30. if (registerValue_ > 0)
  31. {
  32. text = QString("%1\nON").arg(registerId());
  33. }
  34. else
  35. {
  36. text = QString("%1\nOFF").arg(registerId());
  37. }
  38. painter->drawText(QRectF(13, 13, 26, 26), Qt::AlignCenter, text);
  39. painter->restore();
  40. }
  41. if (option->state & QStyle::State_Selected) {
  42. QPen pen(Qt::DashLine);
  43. pen.setColor(Qt::blue);
  44. pen.setWidth(2);
  45. painter->setPen(pen);
  46. painter->setBrush(Qt::NoBrush);
  47. painter->drawRect(boundingRect());
  48. }
  49. }
  50. void Button::addMenuActions(QMenu *menu)
  51. {
  52. menu->addAction("置ON");
  53. menu->addAction("置OFF");
  54. menu->addAction("外观设置");
  55. }
  56. void Button::handleMenuAction(QAction *action)
  57. {
  58. if (action->text() == "复制") {
  59. emit requestCopy(this);
  60. }
  61. if (action->text() == "删除") {
  62. emit requestDelete(this);
  63. }
  64. if (action->text() == "对象"){
  65. emit requestBindRegister(this);
  66. }
  67. if (action->text() == "重置"){
  68. emit requestReset(this);
  69. }
  70. if (action->text() == "置ON"){
  71. emit requestSetON(this, true);
  72. }
  73. if (action->text() == "置OFF"){
  74. emit requestSetON(this, false);
  75. }
  76. if (action->text() == "外观设置"){
  77. QString fileName = QFileDialog::getOpenFileName(nullptr,
  78. "选择图片",
  79. "",
  80. "图片文件(*.png *.jpg *.bmp)");
  81. if (!fileName.isEmpty())
  82. {
  83. setCustomImage(fileName);
  84. }
  85. }
  86. }
  87. void Button::setCustomImage(const QString &imagePath)
  88. {
  89. imagePath_ = imagePath;
  90. loadImage();
  91. update();
  92. }
  93. void Button::loadImage()
  94. {
  95. if(!imagePath_.isEmpty()){
  96. customPixmap_ = QPixmap(imagePath_);
  97. if (!customPixmap_.isNull()){
  98. customPixmap_ = customPixmap_.scaled(50, 50, Qt::KeepAspectRatio, Qt::SmoothTransformation);
  99. }
  100. }
  101. }