• 6889阅读
  • 6回复

怎么样限制在Qwidget上移动的控件的移动范围 [复制链接]

上一主题 下一主题
离线tan_tan_1
 
只看楼主 倒序阅读 楼主  发表于: 2011-06-07
怎么样限制在Qwidget上移动的控件的移动范围,比如,我现在在Qwidget上放了一个按钮,我用鼠标拖动它,但是它的横坐标是10,他只能在横坐标为10的这条线上随鼠标左右移动
离线tlcugb

只看该作者 1楼 发表于: 2011-06-07
用事件过滤器应该可以吧
离线cutemmll
只看该作者 2楼 发表于: 2011-06-08
引用楼主tan_tan_1于2011-06-07 20:03发表的 怎么样限制在Qwidget上移动的控件的移动范围 :
怎么样限制在Qwidget上移动的控件的移动范围,比如,我现在在Qwidget上放了一个按钮,我用鼠标拖动它,但是它的横坐标是10,他只能在横坐标为10的这条线上随鼠标左右移动

楼主的问题很矛盾,应该是纵坐标为10的这条线上左右移动吧。
按照1楼的说法就应该是在事件过滤器里面做一些处理,我写了段代码,实现该功能。
  1. //头文件 widget.h
  2. #ifndef WIDGET_H
  3. #define WIDGET_H
  4. #include <QtGui/QWidget>
  5. #include <QPushButton>
  6. class Widget : public QWidget
  7. {
  8.     Q_OBJECT
  9. public:
  10.     Widget(QWidget *parent = 0);
  11.     ~Widget();
  12. protected slots:
  13.     bool eventFilter(QObject *, QEvent *);
  14. private:
  15.     QPushButton* button;
  16. };
  17. #endif // WIDGET_H

  1. //源文件 widget.cpp
  2. #include <QEvent>
  3. #include <QMouseEvent>
  4. #include "widget.h"
  5. Widget::Widget(QWidget *parent)
  6.     : QWidget(parent)
  7. {
  8.     button = new QPushButton("Move",this);
  9.     button->installEventFilter(this); //安装事件过滤器
  10. }
  11. Widget::~Widget()
  12. {
  13. }
  14. //事件过滤器定义
  15. bool Widget::eventFilter(QObject *, QEvent *evt)
  16. {
  17.     static QPoint lastPnt;
  18.     static bool isHover = false;
  19.     if(evt->type() == QEvent::MouseButtonPress)
  20.     {
  21.         QMouseEvent* e = static_cast<QMouseEvent*>(evt);
  22.         if(button->rect().contains(e->pos()) && //鼠标是否在按键上
  23.                (e->button() == Qt::LeftButton)) //是否是鼠标左键点击
  24.         {
  25.             lastPnt = e->pos();
  26.             isHover = true;
  27.         }
  28.     }
  29.     else if(evt->type() == QEvent::MouseMove && isHover)
  30.     {
  31.         QMouseEvent* e = static_cast<QMouseEvent*>(evt);
  32.         int dx = e->pos().x() - lastPnt.x(); //获取x轴水平移动间距
  33.         button->move(button->x()+dx,button->y());//让按键在原x轴上移动
  34.     }else if(evt->type() == QEvent::MouseButtonRelease && isHover)
  35.     {
  36.         isHover = false;
  37.     }
  38.     return false;
  39. }

我没有做在移动按键时的边界检查,你可以加上


c------------enjoy qt & enjoy life-----------++
离线tlcugb

只看该作者 3楼 发表于: 2011-06-08
应该可以实现!?
离线tan_tan_1
只看该作者 4楼 发表于: 2011-06-09
引用第2楼cutemmll于2011-06-08 13:14发表的  :
楼主的问题很矛盾,应该是纵坐标为10的这条线上左右移动吧。
按照1楼的说法就应该是在事件过滤器里面做一些处理,我写了段代码,实现该功能。
[code]
//头文件 widget.h
.......

我试了一下事件过滤器可以达到基本效果,就是在拖动的时候,按钮有些抖动,有时候会跟着鼠标的拖动,出现在我设定的范围以外,我看帮助里面说是用move就会抖动,我在鼠标释放的时候在设定到我的区域内,也算是解决了
离线cutemmll
只看该作者 5楼 发表于: 2011-06-09
回 4楼(tan_tan_1) 的帖子
那你用我的代码去试下,我当时测试的时候是不会闪烁的
c------------enjoy qt & enjoy life-----------++
离线tan_tan_1
只看该作者 6楼 发表于: 2011-06-10
Re:回 4楼(tan_tan_1) 的帖子
引用第5楼cutemmll于2011-06-09 16:46发表的 回 4楼(tan_tan_1) 的帖子 :
那你用我的代码去试下,我当时测试的时候是不会闪烁的

终于解决了,谢谢
快速回复
限100 字节
 
上一个 下一个