【问题标题】:QT Button Press On WidgetQT 按钮按下小部件
【发布时间】:2015-06-11 04:13:14
【问题描述】:

对使用 Qt 很陌生。我有一个自定义小部件,我需要接收按钮按下,然后从该按钮按下找到鼠标在小部件上的位置。 不幸的是,目前 mousePressEvent(QMouseEvent *me) 似乎无法正常工作。 所以我想知道我到底做错了什么,下面的代码;

头文件:

#ifndef TILESHEETPANE_H
#define TILESHEETPANE_H

#include <QWidget>
#include "global.h"

class tileSheetPane : public QWidget
{
   Q_OBJECT

 public:
     tileSheetPane(int scnWidth, Global *global, QWidget *parent);

 protected:
     void mousePressEvent(QMouseEvent *me);
     void paintEvent(QPaintEvent *);

 private:
     Global *tempGlobal;
     QPoint cursorPos;
     int tileSheetPaneWidth, tileSheetPaneHeight, renderOffsetY;
 };

 #endif // TILESHEETPANE_H

源文件:

   #include <QPainter>
   #include <QMouseEvent>
   #include "tilesheetpane.h"

   //Constructor & Paint Event .. 

   void tileSheetPane::mousePressEvent(QMouseEvent *me)
   {
        cursorPos = me->pos();
   }

CursorPos 的值只是在初始化为 0 时表示。因此,我们将不胜感激任何帮助 :),正如我所说,使用 QT 很新,大概 2 天前才开始,所以我仍在试图弄清楚事情:D。

编辑; 因此,在尝试了 cmets 中的一些建议后,似乎没有任何效果。我确实有 setMouseTracking(true) 但仍然没有。我按照建议在函数中插入了一个 qDebug 调用,似乎 mousePressEvent 永远不会被调用。

 void tileSheetPane::mousePressEvent(QMouseEvent *me)
 {
     cursorPos = me->pos();

     //These Never Show Up!
     qDebug() << me->pos().x();
     qDebug() << me->pos().y();
 }

可能有什么东西正在阻止或阻止这个被调用,但我不确定它可能是什么?

【问题讨论】:

  • 你在做什么看起来是正确的,那么你能说明你是如何确定cursorPos的值的吗?
  • 是的,你显示的代码是正确的。
  • 尝试将QWidget::mousePressEvent(me); 放在重载事件中的cursorPos = me-&gt;pos(); 行之前。我不知道为什么,但在过去,这个电话给我解决了很多麻烦。
  • @cmannett85 - 我通过painter.drawText简单地将cursorPos的值打印到屏幕上; Painter.drawText(50, 50, QString::number(cursorPos.x()));

标签: c++ qt


【解决方案1】:

所以我只是无法让鼠标点击工作,所以在谷歌搜索后,我最终找到了以下视频; http://www.youtube.com/watch?v=E29KiTRYpjk

因为无论如何我的小部件都相当小,我基本上只是重新做了整个事情。但它是值得的。 基本上我删除了我的旧文件,创建了一个 Qt 设计器表单,在我的 mainWindow.ui 文件中添加了一个新的小部件,将它提升为使用“tileSheetPane”,就是这样。现在完美运行:D。

【讨论】:

    【解决方案2】:

    试试这个:

    qDebug() << me->pos()->x();
    

    【讨论】:

      【解决方案3】:

      在 QWidget-child-class 的构造函数中添加 setMouseTracking(true);

      没有这个,您的小部件将无法跟踪鼠标位置。

      MouseTracking property documentation

      【讨论】:

      • 我有,但 PressEvent 仍然没有被捕获。
      • @bali182 这只是确定小部件是否接收鼠标移动事件,即使没有按下按钮。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-25
      • 1970-01-01
      • 2021-10-14
      相关资源
      最近更新 更多