Difference between '&' and '==' while using Qt mouse functions? - c++

I was reading the documentation of Qt example of "scribble". There I stumbled across the following piece of code:
void ScribbleArea::mouseMoveEvent(QMouseEvent *event)
{
if ((event->buttons() & Qt::LeftButton) && scribbling)
drawLineTo(event->pos());
}
void ScribbleArea::mouseReleaseEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton && scribbling) {
drawLineTo(event->pos());
scribbling = false;
}
}
One question arised in my mind on whether there's actually any difference between event->button() == Qt::LeftButton and (event->buttons() & Qt::LeftButton). Could you please explain? Thanks.

The bitwise AND operator (&) compares each bit of the first operand to the corresponding bit of the second operand.
The operator== compare both operands to see if the values are equal.
That is, for you:
event->buttons() & Qt::LeftButton
Will be true if the LeftButton bit is set and other bits may also be set.
event->button() == Qt::LeftButton
Will be true if only the LeftButton bit is set and other bits should not be set.
An example on how it works :
enum
{
BUTTON_LEFT = 1 << 0,
BUTTON_RIGHT= 1 << 1,
BUTTON_MID = 1 << 2
};
int a = 0;
a |= BUTTON_LEFT;
a |= BUTTON_RIGHT;
a |= BUTTON_MID;
if ( a & BUTTON_RIGHT )
std::cout << "The button right is pressed." << std::endl;
if ( a == BUTTON_RIGHT )
std::cout << "There is only the button right." << std::endl;
The output of this will be: The button right is pressed.. http://ideone.com/BunrTs

event->buttons() & Qt::LeftButton
This is true if the LeftButton bit is set; other bits may also be set.
event->button() == Qt::LeftButton
This is true if only the LeftButton bit is set; other bits may not be set.

Looks like a bug to me.
Assuming the mouse buttons are represented as unique bit "flags", the first tests if the left mouse button is pressed, while filtering out any other buttons that might have been pressed at the same time.
The second, however, requires that only the left button has been released. So if you do a double-press to start scribbling, then release both buttons at the same time, it should fail to detect the release.
UPDATE:
This random Qt reference seems to support the assumption, at least:
Qt::LeftButton 0x00000001 The left button is pressed, or an event refers to the left button. (The left button may be the right button on left-handed mice.)
Qt::RightButton 0x00000002 The right button.
Qt::MidButton 0x00000004 The middle button.
Also, as pointed out by brilliant commentor #svk, the two use different ways to access the mouse button flags, so it should be fine.
The fact that release events don't ever report multiple buttons is one of those things you learn after working with Qt for a while, something I haven't done. Sorry for the confusion.

Please note that in case of mouseMoveEvent method event->buttons() is used (it has "s" at the end) and it returns state of multiple buttons. So if many buttons are down many flags will be set.
In contradiction in case of mouseReleaseEvent and mousePressEvent method event->button() is used (no "s" at the end), and this return which button invoke this event this means that only ONE flag is set and it is possible to use equal operator.
When you note that check already excepted answer from Mike Seymour.
Off-topic: in Qt flags have also testFlag method.

Related

Check if left mouse button is held down?

So I am just getting myself into coding using C++ and after learning a bit I started coding an auto clicker. I have already made it so you can toggle the auto clicker using a button on your keyboard or something of that sort, but that isn't what I'm looking for.
The problem I'm having is that I can't seem to find a way to check if the left mouse button is held down. If it is held down, then keep on clicking until the left mouse button is no longer held.
Also, I have looked around a lot to see how to do this, and I have gotten a few different things I should do, but none of them work. I was told to use:
if((GetKeyState(VK_LBUTTON) & 0x100) != 0)
from this answer here, but I also found that people were told to use:
if(GetKeyState(VK_LBUTTON) & 0x8000
Sadly I can't find where I found this in my history.
I have tried getting the key state of WM_LBUTTONDOWN but it doesn't seem to pick up the mouse button is being pressed.
I can get it working by checking the key state of VK_LBUTTON, but that only checks to see if the left mouse button has been pressed, not held. So it just continuously clicks until you break the while loop or close the program.
Not really worth putting this down but my 12 am self, thought that checking if the left button had been pressed (like the one before), it would set a boolean value to true and then keep on clicking. But after that, I couldn't get it to stop like before. Now looking back at the code, I understand why it wasn't working.
while (1) {
if(GetKeyState(WM_LBUTTONDOWN)) {
Sleep(delay);
mouse_event(MOUSEEVENTF_LEFTDOWN, x, y, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, x, y, 0, 0);
std::cout << "Clicked" << endl;
}
if (GetKeyState(VK_ESCAPE)) {
break;
}
}
Like I said before, I have tried all different combinations to try and get this to work. But I can't see if the left mouse button is held down. I hope someone has the answer and can help me out and other people out. Anyways, thanks and have a nice day.
GetKeyState() takes a virtual key code as input, but WM_LBUTTONDOWN is not a virtual key code, it is a window message. Use VK_LBUTTON instead.
Also, GetKeyState() relies on a state machine that is local to the calling thread. That state machine is updated only when the thread processes keyboard/mouse window messages from its message queue. Your code has no such message processing. For what you are attempting, use GetAsyncKeyState() instead.
Also, mouse_event() is deprecated and has been for a long time. Use SendInput() instead.
Try this:
while (GetAsyncKeyState(VK_ESCAPE) >= 0)
{
if (GetAsyncKeyState(VK_LBUTTON) < 0)
{
Sleep(delay);
INPUT input[2] = {};
input[0].type = INPUT_MOUSE;
input[0].mi.dx = x;
input[0].mi.dy = y;
input[0].mi.dwFlags = MOUSEEVENTF_LEFTDOWN;
input[1] = input[0];
input[1].mi.dwFlags = MOUSEEVENTF_LEFTUP;
SendInput(2, input, sizeof(INPUT));
std::cout << "Clicked" << endl;
}
}
I'm not sure whether I understood the q correctly .. but for checking the pressed state you have always to check the lowest bit in the returned high-byte of GetKeyState(VK_LBUTTON) (see GetKeyState() in MSDN-- means:
bool leftButtonPressed = 0 != (GetKeyState(VK_LBUTTON) & 0x800);
WM_LBUTTONDOWN is the message that is send to a window reporting a Left-button-down-event in the client area -- so using that in the GetKeyState() function is wrong. Try
const int delay = 50;
while (1)
{
if (GetKeyState(VK_LBUTTON) & 0x800)
{
Sleep(delay);
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, 0,0, 0, 0);
std::cout << "Clicked" << std::endl;
}
if (GetKeyState(VK_ESCAPE) & 0x800)
{
break;
}
}

c++ - GetAsyncKeyState makes my program crash when I open it

So I'm making a game that runs on the console. I started with some functions to make drawing to the screen easier, and that worked fine. Then when I tried to add input (using the function GetAsyncKeyState), the program crashed as soon as I started the program. It said: "Text Game.exe has stopped working" Here's how I handled the code:
if(GetAsyncKeyState('A' && 0x8000)) {
x -= 1;
}
if(GetAsyncKeyState('D' && 0x8000)) {
x += 1;
}
if(GetAsyncKeyState('W' && 0x8000)) {
y += 1;
}
if(GetAsyncKeyState('S' && 0x8000)) {
y += 1;
}
If it helps, I got this method by reading this:
How to check if a Key is pressed
EDIT: So I ran it in debug mode, and it said it crashed when I ran a function I made called "refreshScreen();". I don't know why though. Here's the code:
void refreshScreen() {
system("CLS");
for ( int i = 0; i < screenHeight; i++ ) {
for ( int j = 0; j < screenWidth; j++ ) {
cout << screen[i][j];
}
cout << endl;
}
}
It's meant to clear the console, then print all of the contents of array "screen". "Screen", by the way, is the buffer that I write to.
If you are trying to use the GetAsyncKeyState as it's described in answers by the link you provided, you are doing it wrong.
Documentation says the following:
If the function succeeds, the return value specifies whether the key was pressed since the last call to GetAsyncKeyState, and whether the key is currently up or down. If the most significant bit is set, the key is down, and if the least significant bit is set, the key was pressed after the previous call to GetAsyncKeyState.
So what is done in the answer by the link you provided:
if (GetAsyncKeyState('W') & 0x8000)
{ /*key is down*/ }
In the if statement there bitwise "and" operation is performed on return value of GetAsyncKeyState function and 0x8000 constant - which equals to 0x8000 the most significant bit is set or equals to 0 when it is not set.
What is your code doing:
if(GetAsyncKeyState('A' && 0x8000)) // ...
logical "and" operation between 'A' and 0x8000 constant - gives true which is casted to 1 and passed to GetAsyncKeyState as an argument.
[EDIT]: As it was mentioned in comments, 1 corresponds to left mouse button. So all if conditions will be true in case left mouse button is down and will be false otherwise. Probably, crash appears in different part of your program after unexpected change of x and y values. You should debug your program to localize the crash.

SDL2 going too fast -- why does it read multiple inputs when I press just one button?

I've started writing an SDL2 program. I want integer count to go up one when the user presses the right arrow key, down one when user presses left.
#include <iostream>
#include <SDL2/SDL.h>
int main(){
SDL_Window *window= SDL_CreateWindow("test", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_SHOWN);
int count= 0;
bool isRunning= true;
SDL_Event ev;
while(isRunning){
if(SDL_PollEvent(&ev)){
if(ev.type == SDL_QUIT || ev.key.keysym.scancode == SDL_SCANCODE_ESCAPE)
return 0;
}
const Uint8 *keystate= SDL_GetKeyboardState(NULL);
if(keystate[SDL_SCANCODE_LEFT])
--count;
else if(keystate[SDL_SCANCODE_RIGHT])
++count;
std::cout << count << std::endl;
}
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
Here's a sample of what's printed when I start the program and briefly tap right -- all within a second or two:
0
0
0
0
0
0
0
0
0
0
0
1
2
3
4
4
4
4
4
When I do a quick tap on the right arrow key, I want count to go up by just one, but instead it went from 0 to 4.
Why?
How do I fix this problem?
Your problem is that you ask SDL for a keystate array, which, in your scenario, is not the best method. So, what does SDL do in this case? It simply gives you an array containing information, wheter the current key is being held or not. You try to press the button as short as you can, but your loop is really quick in time. So, to resolve this, you can use the event system's keydown feature, which gives you true, when you pressed down a button (its pair is the SDL_KEYUP for key released event).
The main difference is in the question: is the key being held, or I just pressed down and changed its state?
So, here is an example (use within the SDL_PumpEvent or SDL_PollEvent):
//...
if (event.type == SDL_KEYDOWN)
{
if (event.key.keysym.sym == SDLK_LEFT)
//do left key things...;
else if (event.key.keysym.sym == SDLK_RIGHT)
//do right key stuff...;
}
//...
Note that this method doesn't use scancodes, but keycodes. (They can produce different result than scancodes, due to different types of keyboards). SDLK_ constants are all keycodes. Moreover (if you think about games), scancodes are good for player movement, keydown events are good for GUI elements
Reference for more information: https://www.libsdl.org/release/SDL-1.2.15/docs/html/guideinputkeyboard.html
I hope you understand!
Lasoloz
Similar to this Question (it actually asks about mouse buttons, but its the same for keyboards):
Instead of using keyboardState use the SDL events. SDL will trigger exactly one event per pressed button, while a fast while-loop can trigger multiple times during a single key-press.
Even though the example is far from being a minimal, complete one and it doesn't compile, I guess that the problem could be due to the lack of a call to SDL_PumpEvents.
As from the documentation:
Note: Use SDL_PumpEvents() to update the state array.
Otherwise, the state array won't be updated, with the results you are experiencing.
NOTE
That said, try to rely on events instead of the internal state array used to represent the keyboard.
EDIT
Updated after the question has been updated.
You should replace the if on SDL_PollEvent with a while, like the following one:
while (SDL_PollEvent(&event)) {
// here you have an event, you can use it
}
Otherwise, even if there are no events, it skips the if and goes through the other statements.
That means that the state of the keyboard won't be updated after the first key press if there are no events, but still you iterate over it.
See here for further details about how SDL_PollEvent works.
I changed the while loops to this:
while(isRunning){
while(SDL_PollEvent(&ev)){
if(ev.type == SDL_QUIT || ev.key.keysym.scancode == SDL_SCANCODE_ESCAPE)
return 0;
else if(ev.type == SDL_KEYDOWN){
if(ev.key.keysym.scancode == SDL_SCANCODE_LEFT){
--count;
std::cout << count << std::endl;
}
else if(ev.key.keysym.scancode == SDL_SCANCODE_RIGHT){
++count;
std::cout << count << std::endl;
}
}
}
}
If I understand it right, SDL_PollEvent fires only while address of object ev is true. If user presses a key down, it continues. If the key is left arrow, count goes down one. If key is right arrow, count increases one.
Now cout prints the way I hoped it would.
Output after I press right a few times:
0
1
2
3
4
Then left:
4
3
2
1
0

SFML Input Not responsive at start

I am making a 2D game where we are supposed to control the character through arrow keys.
if((win.GetInput().IsKeyDown(sf::Key::Down)))
{
y = y + Speed;
}
if((win.GetInput().IsKeyDown(sf::Key::Left)))
{
x = x - Speed;
}
I have set Speed to 10. And then a i use the Sprite.SetPosition(x,y) to actually animate my character.
Everything works fine. But the problem is whenever i press an arrow key, the character moves for 1/2 seconds, stops for about 1/2 seconds and then moves again smoothly. This happens whenever i press any arrow key.
And yes, i am using a while loop on top to handle multiple events simultaneously.
I hope my question was clear enough. Please help me out!
Thanks.
I think you're not handling events the right way. What you're doing here is checking on each event (which could be keyboard input or not) whether the sf::Key::Down key is pressed (and the same for sf::Key::Left).
Firstly, it's not effective, because you don't get the result you want.
Secondly, it performs useless checks admitting that the events could be mouse moves, mouse clicks or anything else : checking whether those keys are pressed in such cases is pointless for your program.
I can't see your whole code, but you should try something of this taste as your main loop :
bool isMovingLeft = false;
bool isMovingDown = false;
sf::Event event;
while (win.IsOpen())
{
// While window catches events...
while(win.GetEvent(event))
{
// If the caught event is a click on the close button, close the window
if (event.Type == sf::Event::Closed)
win.Close();
// If it's a key press, check which key and move consequently
else if (event.Type == sf::Event::KeyPressed)
{
if(event.Key.Code == sf::Key::Left)
isMovingLeft = true;
else if(event.Key.Code == sf::Key::Down)
isMovingDown = true;
}
// If it's a key release, stop moving in the following direction
else if (event.Type == sf::Event::KeyReleased)
{
if(event.Key.Code == sf::Key::Left)
isMovingLeft = false;
else if(event.Key.Code == sf::Key::Down)
isMovingDown = false;
}
}
// Now that we have caught events, we move the lil' thing if we need to.
if(isMovingLeft)
x = x - SPEED;
if(isMovingDown)
y = y - SPEED;
win.Clear();
// Draw things on the screen...
win.Display();
}
In this code, the whole process is split in two parts :
We first intercept the user input to see if we need to change the moving state of the thing.
Then, once every event has been caught and thoroughly analyzed, we move the thing if it has to. It is done through two bools (that you may need to increase to four if you want a four-direction control. If you want to handle diagonal directions, it would be wiser to use an enum than eight bool, which begins to be rather memory-consuming for such a simple task.)
Note : you will maybe notice that I changed "Speed" to "SPEED". I can't see if it was a define, a const var or simply a var from the code you have given, but the best option would be one of the two first ones. I prefer using #define for such things, to make constants easily reachable (as they're put in the preprocessor) and the fully capped writing make it more differentiable from classic vars once in the code. But that's just coding style we're talking of here :)

Multiple movements with keyboard in C++

Im trying to get my movement of a ball to just move in a fluid like motion. How can I have it that when I press the up key, down key, left key, or right key, it doesnt move up one unit, stop, then keep moving. Also, how can i have it move in two directions at the same time wthout stopping another direction when letting off a key?
Thanks
if(GetAsyncKeyState(VK_UP))
{
if(g_nGameState == SETTINGUPSHOT_GAMESTATE || g_nGameState == INITIAL_GAMESTATE)
{
g_cObjectWorld.AdjustCueBallY(MOVEDELTA);
g_cObjectWorld.ResetImpulseVector();
}
}
if(GetAsyncKeyState(VK_DOWN))
{
if(g_nGameState == SETTINGUPSHOT_GAMESTATE || g_nGameState == INITIAL_GAMESTATE)
{
g_cObjectWorld.AdjustCueBallY(-MOVEDELTA);
g_cObjectWorld.ResetImpulseVector();
}
}
if(GetAsyncKeyState(VK_LEFT))
{
if(g_nGameState == SETTINGUPSHOT_GAMESTATE || g_nGameState == INITIAL_GAMESTATE)
{
g_cObjectWorld.AdjustCueBallX(-MOVEDELTA);
g_cObjectWorld.ResetImpulseVector();
}
}
if(GetAsyncKeyState(VK_RIGHT))
{
if(g_nGameState == SETTINGUPSHOT_GAMESTATE || g_nGameState == INITIAL_GAMESTATE)
{
g_cObjectWorld.AdjustCueBallX(MOVEDELTA);
g_cObjectWorld.ResetImpulseVector();
}
}
You can do something like this:
Use SetTimer to create a timer on your window event loop 10ms interval should be good for what you want. The reason it has to be on the window thread is that GetAsyncKeyState will not give you the desired results when called from a different thread.
We use a timer since the call to GetAsyncKeyState should be on a different message then the key processing events so the key is still in the queue.
Within the timer function you can do something like this
int deltaX = 0, deltaY = 0;
unsigned int downDown = GetAsyncKeyState(VK_DOWN);
unsigned int upDown = GetAsyncKeyState(VK_UP);
unsigned int leftDown = GetAsyncKeyState(VK_LEFT);
unsigned int rightDown = GetAsyncKeyState(VK_RIGHT);
if(downDown & 0x00008000)deltaY -= MOVEDELTA;
if(upDown & 0x00008000)deltaY += MOVEDELTA;
if(leftDown & 0x00008000)deltaX -= MOVEDELTA;
if(rightDown & 0x00008000)deltaX += MOVEDELTA;
g_cObjectWorld.AdjustCueBallX(deltaX);
g_cObjectWorld.AdjustCueBallY(deltaY);
g_cObjectWorld.ResetImpulseVector();
In this way you can also make sure that the movement stops on keyup (deltaX == 0 && deltaY == 0)
I'm not sure what are the semantics of AdjustCueBall(X|Y) but if you make sure they stop moving in that direction when they get 0 it should work just fine.
Also you should notice that your keyboard must support multiple key press in the hardware for you to be able to move diagonally using two keys - If it does the solution above will work if it doesn't you will still be able to move in either one of the four fundamental directions.
One design is to use the keyboard only for changing directions.
Let the ball continue in its present direction until a keypress is received that would change its direction. This reduces the load on the processor from continuously being interrupted by keypresses.
As for going in non-orthogonal directions, use more keys. Look at a "keypad". Some keys are diagonal from the '5' keys. Use those.