QGraphicsItem: Why no `stackAfter` method? - qt

I'm having an annoying time trying to get around the 'recommended' way of doing something.
So, I have a stack of cards. I want to make it so that when I deal a card, it becomes the last-drawn object of the entire scene (typical bring_to_front functionality).
The recommended way to do this is just adding to the object's zValue until it is larger than all the rest, but I was hoping to do away with rather "lazy" integers running around all over the place with judicious use of the stackBefore method, which simulates reorganizing the order in which objects were added to the scene.
This works perfectly fine when I shuffle my cards in a limited set (get list of selected items, random.shuffle, for item do item.stackBefore(next item)), but it is certainly not working when it comes to bubbling the card to the top of the entire scene.
I considered adding a copy of the object to the scene and then removing the original, but it just seems like I should be able to do stackAfter like I would when using a Python list (or insertAt or something).
Sample code:
def deal_items(self):
if not self.selection_is_stack():
self.statusBar().showMessage("You must deal from a stack")
return
item_list = self.scene.sorted_selection()
for i,item in enumerate(item_list[::-1]):
width = item.boundingRect().width()
item.moveBy(width+i*width*0.6,0)
another_list = self.scene.items()[::-1]
idx = another_list.index(item)
for another_item in another_list[idx+1:]:
another_item.stackBefore(item)
This works. It just seems somewhat... ugly.

self.scene.items returns the items in the stacking order (link). So if you want to stackAfter an item, you can just query the z value of the current topmost item and then set the z value of the new topmost card to a value one larger.
item.setZValue(self.scene.items().first().zValue() + 1)
Hope that helps.
Edit added src for stackBefore and setZValue from http://gitorious.org/qt/
src/gui/graphicsview/qgraphicsitem.cpp
void QGraphicsItem::stackBefore(const QGraphicsItem *sibling)
{
if (sibling == this)
return;
if (!sibling || d_ptr->parent != sibling->parentItem()) {
qWarning("QGraphicsItem::stackUnder: cannot stack under %p, which must be a sibling", sibling);
return;
}
QList<QGraphicsItem *> *siblings = d_ptr->parent
? &d_ptr->parent->d_ptr->children
: (d_ptr->scene ? &d_ptr->scene->d_func()->topLevelItems : 0);
if (!siblings) {
qWarning("QGraphicsItem::stackUnder: cannot stack under %p, which must be a sibling", sibling);
return;
}
// First, make sure that the sibling indexes have no holes. This also
// marks the children list for sorting.
if (d_ptr->parent)
d_ptr->parent->d_ptr->ensureSequentialSiblingIndex();
else
d_ptr->scene->d_func()->ensureSequentialTopLevelSiblingIndexes();
// Only move items with the same Z value, and that need moving.
int siblingIndex = sibling->d_ptr->siblingIndex;
int myIndex = d_ptr->siblingIndex;
if (myIndex >= siblingIndex) {
siblings->move(myIndex, siblingIndex);
// Fixup the insertion ordering.
for (int i = 0; i < siblings->size(); ++i) {
int &index = siblings->at(i)->d_ptr->siblingIndex;
if (i != siblingIndex && index >= siblingIndex && index <= myIndex)
++index;
}
d_ptr->siblingIndex = siblingIndex;
for (int i = 0; i < siblings->size(); ++i) {
int &index = siblings->at(i)->d_ptr->siblingIndex;
if (i != siblingIndex && index >= siblingIndex && index <= myIndex)
siblings->at(i)->d_ptr->siblingOrderChange();
}
d_ptr->siblingOrderChange();
}
}
void QGraphicsItem::setZValue(qreal z)
{
const QVariant newZVariant(itemChange(ItemZValueChange, z));
qreal newZ = newZVariant.toReal();
if (newZ == d_ptr->z)
return;
if (d_ptr->scene && d_ptr->scene->d_func()->indexMethod != QGraphicsScene::NoIndex) {
// Z Value has changed, we have to notify the index.
d_ptr->scene->d_func()->index->itemChange(this, ItemZValueChange, &newZ);
}
d_ptr->z = newZ;
if (d_ptr->parent)
d_ptr->parent->d_ptr->needSortChildren = 1;
else if (d_ptr->scene)
d_ptr->scene->d_func()->needSortTopLevelItems = 1;
if (d_ptr->scene)
d_ptr->scene->d_func()->markDirty(this, QRectF(), /*invalidateChildren=*/true);
itemChange(ItemZValueHasChanged, newZVariant);
if (d_ptr->flags & ItemNegativeZStacksBehindParent)
setFlag(QGraphicsItem::ItemStacksBehindParent, z < qreal(0.0));
if (d_ptr->isObject)
emit static_cast<QGraphicsObject *>(this)->zChanged();
}

Related

Is there an efficient algorithm for calculating which tiles are within a set walking distance of your character in a 2d grid?

Lets say that on a 2d grid of 20x20, you have your character at position (5,5).
He is able to walk up to 4 tiles in his move. However, there may be obstacles blocking your path such as a wall.
Is there any efficient / easy way for calculating exactly which tiles he would be able to walk to without checking every single possible move ( e.g. move up 0 and right 0 then move up 0 and right 1 e.t.c )?
At the moment I'm calculating the places that you can walk through with this horrific thing:
int playerx = GridPane.getRowIndex(button);
int playery = GridPane.getColumnIndex(button);
int position = playery*8+playerx;
for (int i = 0; i < 5; i++)
{
for (int j = i-4; j < 5-i; j++)
{
try
{
int expectedCollumn = playerx+j;
int actualCollumn = ((position+i+j*8)-((position+i+j*8)%8))/8;
if(expectedCollumn==actualCollumn)
{
Button temp = (Button)gridPane.getChildren()
.get(position+i+j*8);
if (!temp.getText().equals("W") &&
!temp.getText().equals("P"))
{
temp.setText("T");
}
}
actualCollumn = ((position-i+j*8)-((position-i+j*8)%8))/8;
if(expectedCollumn==actualCollumn)
{
Button temp2 = (Button)
gridPane.getChildren().get(position-i+j*8);
if (!temp2.getText().equals("W") &&
!temp2.getText().equals("P"))
{
temp2.setText("T");
}
}
}
}
}
However, its showing as if you are able to walk to the otherside of the wall and I'm not sure how I would go about fixing this.
Many thanks in advance.
For path finding, you should figure out how this works:
https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
and then move on to A* or something more efficient.
Thanks to everyone that answered but the solution was simple
incase somehow someone finds this post and is interested it was a simple recursive call
void getReachableTiles(Tile current, Int stamina, List<Tile> visited, List<Tile> reachable) {
if (stamina <= 0) return;
List<Tile> neighbours = new List<>(current + up, current + left, ..)
for (Tile t in neighbours) {
if (!visited.contains(t)) {
visited.append(t);
if (!t.isWall()) {
reachable.append(t);
getReachableTiles(t, stamina - 1, visited, reachable);
}
}
}
}

Qt GraphicsEllipseItem numbering

So I'm building this app in which I click on the graphicsView and a ellipse appears at the exact location where I clicked. All good and nice, now I want to number these ellipses. I want to set a text inside the ellipse. Like, when I click the first time on the graphicsView a ellipse shows up and inside it's written "1", then i click somewhere else again and another ellipse shows up, this time with the text "2" and so on...
Create a class to draw the ellipse,deriving from QGraphicsEllipseItem (maybe this is already done)
Insert the ellipse into the scene with scene->addItem()
The move the ellipse with setpos()
In that class create a static member static int ellipse_count and initialise it to 0. Increase that counter everytime you create an ellipse, and decrease it everytimeyou destroy one (put the code increasing and decreasing the counter in the constructor and destructor)
You can add a member to your ellipse class as a QGraphicsTextItem and create the object and place it inside the ellipse constructor. This way you can place the Text itemin relative coordinate inside the ellipse referential and it will move with the ellipse.
void Widget::mousePressEvent(QMouseEvent *mouseEvent)
{
QPointF p = mouseEvent->localPos();
if (mouseEvent->button() == Qt::LeftButton &&
p.x() >= 20 && p.x() <= 780 && p.y() >= 20 && p.y() <= 780)
{
int l = 40;
count++;
elipse[count] = scene->addEllipse(p.x()-l/2-14, p.y()-l/2-14, l, l, QPen(Qt::black));
elipse[count]->setFlags(QGraphicsEllipseItem::ItemIsMovable)
}
}
So this is the function. I want to add text, and DO NOT forget, the item is MOVABLE, so if the item moves, the text must also move.
EDIT!
I Figured it out!
void Widget::mousePressEvent(QMouseEvent *mouseEvent)
{
QPointF p = mouseEvent->localPos();
if (mouseEvent->button() == Qt::LeftButton &&
p.x() >= 20 && p.x() <= 780 && p.y() >= 20 && p.y() <= 780)
{
int l = 40;
count++;
elipse[count] = scene->addEllipse(p.x()-l/2-14, p.y()-l/2-14, l, l, QPen(Qt::black));
elipse[count]->setFlags(QGraphicsEllipseItem::ItemIsMovable);
enumbering[count] = scene->addSimpleText(QString::number(count));
enumbering[count]->setPos(p.x()-l/2+3, p.y()-l/2-1);
enumbering[count]->setParentItem(elipse[count]);
}
}

Recursive Sudoku Solver- Segmentation Fault (C++)

I'm attempting to make a sudoku solver for the sake of learning to use recursion. I seem to have gotten most of the code to work well together, but when I run the program, I get a windows error telling me that the program has stopped working. A debug indicates a segmentation fault, and I saw elsewhere that this can be caused by too many recursions. I know this is a brute-force method, but again, I'm more worried about getting it to work than speed. What can I do to fix this to a working level?
struct Playing_grid {
//Value of cell
int number;
//wether the number was a clue or not
bool fixed;
}
grid[9][9];
void recursiveTest(int row, int column, int testing)
{
//first, check to make sure it's not fixed
if(grid[row][column].fixed == false)
{
if((checkRow(testing, row) | checkColumn(testing, column) | checkBox(testing,boxNumber(row,column)) | (testing > 9)) == 0)
{
grid[row][column].number = testing;
moveForward(row,column,testing);
recursiveTest(row, column, testing);
}
else if(testing < 9)
{
testing ++;
recursiveTest(row, column, testing);
}
else if(testing == 9)
{
while(testing == 9)
{
moveBack(row,column,testing);
while(grid[row][column].fixed == true)
{
{
moveBack(row,column,test);
}
}
testing = grid[row][column].number;
recursiveTest(row,column,testing);
}
}
}
else
{
moveForward(row,column,testing);
recursiveTest(row,column,testing);
}
}
void moveForward(int& row, int& column, int& test)
{
if(column < 8)
{
column ++;
}
else if((column == 8) & (row != 8))
{
column = 0;
row ++;
}
else if((column == 8) & (row == 8))
{
finishProgram();
}
test = 1;
}
void moveBack(int& row, int& column, int& test)
{
grid[row][column].number = 0;
if(column > 0)
{
column --;
}
else if((column == 0) & (row > -1))
{
column = 8;
row --;
}
else
{
cout << "This puzzle is unsolveable!" << endl;
}
test++;
}
I tried to include all the relevant pieces. I essentially create a 9x9 matrix, and by this point it is filled with 81 values, where empty slots are written as 0. After confirming the test value is valid in the row, column and box, it fills in that value and moves onto the next space. Whenever it runs to 9 and has no possible values, it returns to the previous value and runs through values for that one.
So as to not overwrite known values, the recursive function checks each time that the value of the grid[row][column].fixed is false.
I'd appreciate any insight as to cleaning this up, condensing it, etc. Thanks in advance!
Edit: To exit the recursive loop, when the function is called to move forward, if it has reached the last cell, it completes (saves + outputs) the solution. The code has been adjusted to reflect this.
I'd normally try to fix your code, but I think in this case it's fundamentally flawed and you need to go back to the drawing board.
As a general rule, the pseudocode for a recursive function like this would be
For each possible (immediate) move
Perform that move
Check for win state, if so store/output it and return true.
Call this function. If it returns true then a win state has been found so return true
Otherwise unperform the move
Having tried every move without finding a win state, return false.

Collision Detection and maintaining momentum on an object

I have been implementing various forms of simple collision detection with varying results. I have a fairly good working version of collision detection, but there are some odd behaviors that I can't work out.
Just for a reference, i'm making a simple pong game, and trying to refine the collision. The problems I get are when the ball collides with the paddle on either the top or bottom side. In those cases, the ball hovers above (or below) the paddle and does not move. I'm guessing this is because of how i'm checking for collision and how i'm altering the movespeed of the ball.
I would like to implement a way I differentiate between top/bottom and left/right collision but this is the only method that works decently:
static void CheckCollision(PActor object1, PActor object2, PInput pinput)
{
if ( CheckObjectCollision( object1, object2 ) )
{
AdjustMoveSpeed( object1, object2, pinput );
}
}
static bool CheckObjectCollision(PActor object1, PActor object2)
{
int object1LeftBound = object1.position.x;
int object1RightBound = object1.position.x + object1.actorTextureXSize;
int object1TopBound = object1.position.y;
int object1BottomBound = object1.position.y + object1.actorTextureYSize;
int object2LeftBound = object2.position.x;
int object2RightBound = object2.position.x + object1.actorTextureXSize;
int object2TopBound = object2.position.y;
int object2BottomBound = object2.position.y + object2.actorTextureYSize;
if ( object1RightBound < object2LeftBound )
return false;
if ( object1LeftBound > object2RightBound )
return false;
if ( object1BottomBound < object2TopBound )
return false;
if ( object1TopBound > object2BottomBound )
return false;
return true;
}
I am guessing that the root of some of the problems i'm having is the function AdjustMoveSpeed, here it is:
static void AdjustMoveSpeed(PActor object1, PActor object2, PInput pinput)
{
PVector prevMouseLocation = pinput.GetPrevMouseLocation();
PVector currMouseLocation = pinput.GetCurrMouseLocation();
int currentMoveSpeed;
int nextMoveSpeed;
if (typeid(object1) == typeid(PBall))
{
object1.moveSpeed.x *= -1;
if ( typeid(object2) == typeid(PPlayer) )
{
currentMoveSpeed = object1.moveSpeed.y;
nextMoveSpeed = prevMouseLocation.y - currMouseLocation.y;
object1.moveSpeed.y = (prevMouseLocation.y - currMouseLocation.y) * -1;
}
else
{
if (object1.moveSpeed.y > 0)
object1.moveSpeed.y *= -1;
}
}
else if (typeid(object2) == typeid(PBall))
{
object2.moveSpeed.x *= -1;
if ( typeid(object1) == typeid(PPlayer) )
{
currentMoveSpeed = object1.moveSpeed.y;
nextMoveSpeed = prevMouseLocation.y - currMouseLocation.y;
object2.moveSpeed.y = (prevMouseLocation.y - currMouseLocation.y) * -1;
}
else
{
if (object2.moveSpeed.y > 0)
object2.moveSpeed.y *= -1;
}
}
}
What I was attempting to do with AdjustMoveSpeed, is first check to see which object is the ball, after this, multiply the x move speed by -1 to reverse its direction. After this, I check to see if the other object is a player, if so I set the y move speed to the difference between the previous mouse location and current mouse location. This is here to give the player option to change the balls y speed, or add spin.
I've tried checking for intersection between objects so that I can get a specific side, and the result is the ball just flying in the middle of the screen without actually hitting either paddle.
How do I properly check for collision detection on two objects that are squares?
How can I fix AdjustMoveSpeed so that it works properly with collision detection?
Lastly, how do I keep the momentum of the ball of its current speed is greater than the difference of the mouse location before and after the hit?
I've tried taking comparing the absolute value of currentMoveSpeed and nextMoveSpeed but then the ball doesn't change y speed. Something like this:
if ( abs(currentMoveSpeed) < abs(nextMoveSpeed )
object1.moveSpeed.y = (prevMouseLocation.y - currMouseLocation.y) * -1;
else
object1.moveSpeed.y *= -1
Pong is simple enough that, rather than moving the ball each frame and checking for a collision with a paddle, you can actually solve the equation for when the paddle and ball will collide - if that time is less than one frame, there is a collision.
This completely eliminates the issue of the ball moving so fast it moves through the paddle, an issue that plagues many pong-clones that use the naive method of collision-detection.
This solution is called continuous collision detection - see this answer for more information.
If the ball gets stuck on the paddle instead of bouncing it is probably because it keeps changing direction back and forth. The ball should only bounce if it is heading towards the paddle.
if (sgn(object1.moveSpeed.x) == sgn(object1.x - object2.x)) {
// Ball is already moving away from the paddle, don't bounce!
}
else {
// Ok to bounce!
object1.moveSpeed.x *= -1;
}

QTableView and horizontalHeader()->restoreState()

I can't narrow down this bug, however I seem to have the following problem:
saveState() of a horizontalHeader()
restart app
modify model so that it has one less column
restoreState()
Now, for some reason, the state of the headerview is totally messed up. I cannot show or hide any new columns, nor can I ever get a reasonable state back
I know, this is not very descriptive but I'm hoping others have had this problem before.
For QMainWindow, the save/restoreState takes a version number. QTableView's restoreState() does not, so you need to manage this case yourself.
If you want to restore state even if the model doesn't match, you have these options:
Store the state together with a list of the columns that existed in the model upon save, so you can avoid restoring from the data if the columns don't match, and revert to defualt case
Implement your own save/restoreState functions that handle that case (ugh)
Add a proxy model that has provides bogus/dummy columns for state that is being restored, then remove those columns just afterwards.
I personally never use saveState()/restoreState() in any Qt widget, since they just return a binary blob anyway. I want my config files to be human-readable, with simple types. That also gets rid of these kind of problems.
In addition, QHeaderView has the naughty problem that restoreState() (or equivalents) only ever worked for me when the model has already been set, and then some time. I ended up connecting to the QHeaderView::sectionCountChanged() signal and setting the state in the slot called from it.
Here is the solution I made using Boost Serialization.
It handles new and removed columns, more or less. Works for my use cases.
// Because QHeaderView sucks
struct QHeaderViewState
{
explicit QHeaderViewState(ssci::CustomTreeView const & view):
m_headers(view.header()->count())
{
QHeaderView const & headers(*view.header());
// Stored in *visual index* order
for(int vi = 0; vi < headers.count();++vi)
{
int li = headers.logicalIndex(vi);
HeaderState & header = m_headers[vi];
header.hidden = headers.isSectionHidden(li);
header.size = headers.sectionSize(li);
header.logical_index = li;
header.visual_index = vi;
header.name = view.model()->headerData(li,Qt::Horizontal).toString();
header.view = &view;
}
m_sort_indicator_shown = headers.isSortIndicatorShown();
if(m_sort_indicator_shown)
{
m_sort_indicator_section = headers.sortIndicatorSection();
m_sort_order = headers.sortIndicatorOrder();
}
}
QHeaderViewState(){}
template<typename Archive>
void serialize(Archive & ar, unsigned int)
{
ar & m_headers;
ar & m_sort_indicator_shown;
if(m_sort_indicator_shown)
{
ar & m_sort_indicator_section;
ar & m_sort_order;
}
}
void
restoreState(ssci::CustomTreeView & view) const
{
QHeaderView & headers(*view.header());
const int max_columns = std::min(headers.count(),
static_cast<int>(m_headers.size()));
std::vector<HeaderState> header_state(m_headers);
std::map<QString,HeaderState *> map;
for(std::size_t ii = 0; ii < header_state.size(); ++ii)
map[header_state[ii].name] = &header_state[ii];
// First set all sections to be hidden and update logical
// indexes
for(int li = 0; li < headers.count(); ++li)
{
headers.setSectionHidden(li,true);
std::map<QString,HeaderState *>::iterator it =
map.find(view.model()->headerData(li,Qt::Horizontal).toString());
if(it != map.end())
it->second->logical_index = li;
}
// Now restore
for(int vi = 0; vi < max_columns; ++vi)
{
HeaderState const & header = header_state[vi];
const int li = header.logical_index;
SSCI_ASSERT_BUG(vi == header.visual_index);
headers.setSectionHidden(li,header.hidden);
headers.resizeSection(li,header.size);
headers.moveSection(headers.visualIndex(li),vi);
}
if(m_sort_indicator_shown)
headers.setSortIndicator(m_sort_indicator_section,
m_sort_order);
}
struct HeaderState
{
initialize<bool,false> hidden;
initialize<int,0> size;
initialize<int,0> logical_index;
initialize<int,0> visual_index;
QString name;
CustomTreeView const *view;
HeaderState():view(0){}
template<typename Archive>
void serialize(Archive & ar, unsigned int)
{
ar & hidden & size & logical_index & visual_index & name;
}
};
std::vector<HeaderState> m_headers;
bool m_sort_indicator_shown;
int m_sort_indicator_section;
Qt::SortOrder m_sort_order; // iff m_sort_indicator_shown
};
I would expect it to break if you change the model! Those functions save and restore private class member variables directly without any sanity checks. Try restoring the state and then changing the model.
I'm attempting to fix this issue for Qt 5.6.2, after hitting the same issue. See
this link for a Qt patch under review, which makes restoreState() handle the case where the number of sections (e.g. columns) in the saved state does not match the number of sections in the current view.

Resources