- Setmousetracking qt не работает
- Не удается правильно отследить движения мыши, setMouseTracking не имеет никакого эффекта — Qt
- Решение
- Другие решения
- QT setMouseTracking(true) has no effect at all
- 1 Answer 1
- Not the answer you’re looking for? Browse other questions tagged c++ qt or ask your own question.
- Related
- Hot Network Questions
- Subscribe to RSS
- Thread: another setMouseTracking(true) not working; QWidget
- another setMouseTracking(true) not working; QWidget
- Re: another setMouseTracking(true) not working; QWidget
- Re: another setMouseTracking(true) not working; QWidget
- Re: another setMouseTracking(true) not working; QWidget
- Re: another setMouseTracking(true) not working; QWidget
- Re: another setMouseTracking(true) not working; QWidget
- Re: another setMouseTracking(true) not working; QWidget
- Re: another setMouseTracking(true) not working; QWidget
- Re: another setMouseTracking(true) not working; QWidget
- Re: another setMouseTracking(true) not working; QWidget
- Re: another setMouseTracking(true) not working; QWidget
- Re: another setMouseTracking(true) not working; QWidget
- Re: another setMouseTracking(true) not working; QWidget
- Re: another setMouseTracking(true) not working; QWidget
- Re: another setMouseTracking(true) not working; QWidget
- Re: another setMouseTracking(true) not working; QWidget
- Re: another setMouseTracking(true) not working; QWidget
- Re: another setMouseTracking(true) not working; QWidget
- Re: another setMouseTracking(true) not working; QWidget
- Re: another setMouseTracking(true) not working; QWidget
Setmousetracking qt не работает
разработчик РЭА
Группа: Сомодератор
Сообщений: 9668
Регистрация: 9.1.2008
Из: Тюмень
Пользователь №: 64
Репутация: 94
NordWest, проверь как работает пример %QTDIR%\examples\widgets\scribble
измени файл scribblearea.cpp
в конце конструктора добавь строку:
setMouseTracking ( true);
А в функции void ScribbleArea::mouseMoveEvent(QMouseEvent *event), закоментируй строчку условия, чтобы осталась только функция
drawLineTo(event->pos());
собери и посмотри, должно рисоватся без участия кнопки мыши.
Профессионал
Группа: Участник
Сообщений: 1207
Регистрация: 8.12.2008
Из: Russia, Moscow
Пользователь №: 446
Репутация: 34
Таким образом пропиши:
Студент
Группа: Участник
Сообщений: 86
Регистрация: 26.11.2008
Пользователь №: 433
Репутация: 0
Ну да, работает. И у меня вызывается, если mouseMoveEvent() центрального виджета MainWindow вызывать, а не MainWindow().
Мне бы подошло, но информацию о положении мыши надо выдавать в строку состояния, а как я это сделаю из под виджета.
Таким образом пропиши:
Таким образом всё работает двояко.
Если я создаю метод mouseMoveEvent (переопределяю наверное) в классе центрального виджета, то происходит следующее.
При движении мышки над центральным виджетом (картинка) трэкинг не работает, но mouseMoveEvent вызывается, тот что в классе центрального виджета. Если его не определять, то вызывается mouseMoveEvent у MainWindow и только с нажатием кнопки, т.е. без трэкинга.
При этом, при движении мыши над окном вне центрального виджета, трэкинг работает и координаты мышки выводятся в строку состояния.
Профессионал
Группа: Участник
Сообщений: 1207
Регистрация: 8.12.2008
Из: Russia, Moscow
Пользователь №: 446
Репутация: 34
Потому, что переопределил одновременно и у главного окна и у центрального виджета. События передаются виджетам по-цепочке, можешь в QMainWindow::mouseMoveEvent сделать accept и событие дальше не пойдет.
Когда ты водишь мышкой по главному окну — ты водишь мышкой над центральным виджетом. Изначально mouseTracking отключен у окон, в итоге этот центральный виджет не ловит и не пересылает события мыши другим окнам. Поэтому мы сначала ставим трэкинг у него, чтобы события начались пересылаться, но т.к. у главного окна тоже трэкинг вырублен, то он события мышки просто игнорит, после того как включаем — он начинает реагировать. Проще переопределить mouseMoveEvent у QMainWindow вместо того, чтобы вызывать installEventFilter у центрального виджета или создавать свой центральный виджет. Но в принципе будет правильным это сделать.
Источник
Не удается правильно отследить движения мыши, setMouseTracking не имеет никакого эффекта — Qt
Я работаю над проектом, который был начат кем-то другим, поэтому я не могу изменить структуру кода.
Код моего класса следующий (это всего лишь пример):
Итак, мой класс содержит «окно» QmainWindow и пользовательский виджет «zone_notif» (в основном прямоугольник). Я хочу отобразить сообщение, когда курсор мыши проходит над «zone_notif», и другое сообщение, когда оно появляется.
Сначала я попробовал следующее:
Но это работает, только если я нажму кнопку мыши, прежде чем двигаться.
Я нашел грязное решение:
Но это решение не правильно. Мое приложение содержит другие окна, и если я установлю свой полноэкранный режим QMainWindow, я никогда не выхожу из него, поэтому другие мои окна больше не будут активными.
Я пытался изменить window->setMouseTracking(true) в zone_notif->setMouseTracking(true) и то же самое с «nstallEventFilter», но это не имеет никакого эффекта.
Я также попытался переопределить mouseMoveEvent:
Но это никогда не вызывается.
У вас есть идея, как я могу заставить это работать?
Решение
Переопределить QWidget :: mouseMoveEvent (QMouseEvent * event)
Вы должны получить событие, когда включено отслеживание мыши.
Другие решения
Я нашел решение.
Чтобы наверняка перехватить событие перемещения мыши, я установил фильтр событий в своем приложении QApplication.
Я создал новый класс «myEventFilter», и этот класс устанавливается как фильтр событий.
Источник
QT setMouseTracking(true) has no effect at all
so here is my code, I am trying to capture mouse input which does not work unless I hold down my left key on my mouse. Keyboard input works perfectly fine.
For some reason the mouse movement is not captured? I am calling setMouseTracking but I receive no data. I am relatively new to QT and C++ and am making this application in response to a UI demanded by a client.. So what I am trying to achieve is to get the mouse x,y for only inside the Widget.
1 Answer 1
You need to enable mouse tracking for the widgets the mouse is actually on. It seems you have child widgets. Those child widgets need to have mouse tracking enabled so that they propagate the mouse move events to their parent.
You can just call setMouseTracking(true); once. You don’t need to enable/disable mouse tracking when the mouse enters/leaves. That means you don’t need enterEvent() and leaveEvent() handlers.
Not the answer you’re looking for? Browse other questions tagged c++ qt or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.10.18.40487
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Источник
Thread: another setMouseTracking(true) not working; QWidget
Thread Tools
Search Thread
Display
another setMouseTracking(true) not working; QWidget
I am trying to enable mouseTracking in a widget subclassed from QWidget. Here’s the subclassed QWidget
and the constructor for the main window which instantiates the CoinWidget object:
um, as you can see I’ve tried to setMouseTracking(true) 4 different ways, none of which is successful. I saw in the setMouseTracking/QCanvasView posts, you need to do it via the viewport(). But what about my example: if the widget in which you want to enable mouseTracking is subclassed from QWidget?
Re: another setMouseTracking(true) not working; QWidget
Are you trying to receive mouse move events on the coin widget?
Have you installed any event filters on it? Because usually it is not required to do this. It receives mouse move events by default.
Re: another setMouseTracking(true) not working; QWidget
yes, only on the CoinWidget. I want to pass event->x() and event->y() on to another part of the program. The only way I know how to get their values is to include a QMouseEvent. The problem is: I can only get the values when the mouse button is pushed. Are you suggesting there’s another way to get these values, whether or not a mouse button is pushed?
hmmm, there are no event filters on it (unless QMouseEvent is considered a «filter»).
Re: another setMouseTracking(true) not working; QWidget
So mouseMoveEvent does not get called. That is not normal.
Are you sure there is nothing covering the widget?
Perhaps more code would help.
Re: another setMouseTracking(true) not working; QWidget
mouseMoveEvent *is* getting called. but only when the button is pushed. I think I’m not using setMouseTracking(true) properly.
Re: another setMouseTracking(true) not working; QWidget
my bad (perhaps): i *do* have an event filter for the myWindow class (the main Window, in which CoinWidget is instantiated), something like:
. I wouldn’t think this is the problem, though, since mousing over the CoinWidget window shouldn’t be caught by this filter (which catches some mousing over specific buttons not in the CoinWidget window).
Re: another setMouseTracking(true) not working; QWidget
No, here must be it. What class is the main window? Is it QWidget or QMainWindow?
Because you should call QMainWindow::eventFilter not QWidget.
And the common practice is to test first for the target object and then for the event type, not the other way around. Take a look at the eventFilter documentation. There is an example there.
Re: another setMouseTracking(true) not working; QWidget
actually, the main window class is QWidget, not QMainWindow. (I have a couple questions about this that I’ll post in another thread later.) Anyway, since the main Window is a QWidget, I assume it’s correct to call QWidget::eventFilter?
I’ll look more into this. The myWidget example here tests event type first, then object, but perhaps this is a special case. But this doesn’t seem to be the problem, anyway: when I comment the eventFilter out of my Main Window, the mouseEvent is still behaving the same way. In other words, this function:
is only called when I press/hold a mouseButton *before* moving the mouse. Thanks for helping me narrow it down, though.
Re: another setMouseTracking(true) not working; QWidget
I feel you still have something wrong in your eventFilter code. Did you comment out the function both in declaration and definition or just commented function body ? Try calling return QWidget::eventFilter(obj,e); in the body of event filter defined by you in the beginning itself instead of just commenting.
If everything is proper may be you have installed event filter for QApplication, did you check for this ?
The following example works fine for me
EDIT: Actually your event filter code seems to be proper(even without commenting). So my guess is there is one more event filter(may be installed on qapp) which is causing malfunction in your case.
Last edited by Gopala Krishna; 3rd September 2007 at 19:25 .
Re: another setMouseTracking(true) not working; QWidget
. this has become hugely frustrating. Thanks, GK- yeah, your example worked for me, too. I tinkered w/the HelloGL, as well, and it works. I even included the glwidget.h/.cpp file in my own application (i replaced coinWidget with the glWidget), turned on MouseTracking, at it works.
But nothing I do with coinWidget will work! I even tried commenting the moveMouseEvent feature in the mainWindow class, then editing the mainWindow eventFilter like so:
but still only see «eventFilter: hello» if I click/drag the mouse button (on coinWidget). Other widgets with both installEventFilter() and setMouseTracking(true), however, work as expected.
So: the problem has to be my coinWidget class. This is a container widget for a coin3d scenegraph. Perhaps the SoQt widget embedded in the coinWidget is grabbing the moveMouseEvent even before Qt can? But I wouldn’t think this could happen. Anyway, I’m posting the coinWidget code below. See anything.
Re: another setMouseTracking(true) not working; QWidget
Well, you didn’t mention this before.
This is the reason. It happened to me lots of times.
The fix is to install an event filter on the child wiidget. Do what you want with the event, but make sure to forward it to the child, in case it needs it.
Re: another setMouseTracking(true) not working; QWidget
I was all set to donate a few kopeks to the Ceauseascu Center for Historical Revisionism in your honor. when I realized I don’t know what you’re talking about (yet).
I tried that (i think), above: «coinWidget->installEventFilter(this);» . or what am I missing?
Re: another setMouseTracking(true) not working; QWidget
Forget Ceausescu
.
What you’re missing (I think) is that you have to install an event filter for the widget contained within the coin widget(I don’t know what is called), because that is the one that’s eating all the mouse move events for your widget.
So, what do you have inside the coin widget?
Re: another setMouseTracking(true) not working; QWidget
the coinWidget constructor is basically:
and the constructor for Model:
so you’re suggesting that I add an eventFilter to the Model class to intercept the mouseMovements? I’ll try this. It does seem odd that I can intercept the mouseMovements at the application/mainWindow level, but only if the mouse-button is pushed/dragged.
ok, we’ll bag Ceauseascu for now. . maybe Vlad? I just listened to a podcast about the famed Impaler a couple days ago. tisk tisk: everyone knows the humane way to slaughter folks is from a B-52.
(sorry, gettin’ off-topic here)
Re: another setMouseTracking(true) not working; QWidget
Install the event filter on the baseWidget of Model.
Does it have a getter for it?
Re: another setMouseTracking(true) not working; QWidget
I don’t understand what the BaseWidget is. It looks to me like in:
QWidget *widget = this->buildWidget(this->getParentWidget());
widget is a pointer to the coinWidget class/object? So
is setting baseWidget to the coinWidget? I don’t know what a getter is.
Re: another setMouseTracking(true) not working; QWidget
void SoQtComponent::setBaseWidget(QWidget * widget) [protected]
Set the core widget for this SoQt component. It is important that subclasses get this correct, as the widget set here will be the widget returned from query methods.
from the SoQtExaminerViewer documentation.
EDIT: isn’t «the widget set here» in my case the CoinWidget?
QWidget * SoQtFullViewer::buildWidget (QWidget * parent ) [protected]
This method builds the component contents in the given parent widget. For subclasses adding new user interface items, this method is typically overridden in the following manner:
QWidget * MyOwnViewer::buildWidget(QWidget * parent)
<
QWidget * superw = ::buildWidget(parent);
// [then move superw within MyOwnViewer framework and add own
// user interface components]
>
Re: another setMouseTracking(true) not working; QWidget
If it has a setter( setBaseWidget) then it also should have a getter( getBaseWidget or baseWidget).
You need a function in the model that returns the widget created in the constructor( widget ). The event filter has to be installed on that widget.
Re: another setMouseTracking(true) not working; QWidget
gotcha. yeah, there’s a getBaseWidget.
Re: another setMouseTracking(true) not working; QWidget
I’ve sort of been watching this thread from a distance. I’m at work a the moment so I can’t view the Coin3d, or the code we played with a while back, source, but in the original thread starter on http://www.qtcentre.org/forum/f-newb. lots-6895.html you used to have a line
that created a SoQtExaminerViewer within the CoinWidget. This effectively overlays a coin opengl rendering window over your QWidget, and hooks in the Coin model. I’ve been trying to read the coin source SVN respository but its responding slowly — but its possible that on Windows this is done by subclassing the native WindowProc. The Coin3d / OIV viewers don’t inherit from QWidget, so event won’t bubble up the heirarchy chain — I’ll take look at the coin source tonight on my pc to check how its linked in. But some of the coin examples show classes inherited from SoQt. Viewer as well as QWidget.
This might mean that trying to hook a Qt event filter won’t work in this way, and this is what your seeing.
p.s Missed all the latest posts!
Last edited by pdolbey; 5th September 2007 at 14:10 . Reason: postscript added
Источник