I try to use QGraphicsView to display a map with some QGraphicItem-subclass showing region centers of the map. Conceptually, I organize the map as follow:
QGraphicsView
QGraphicsScene
QGraphicsPixmapItem : background image, fixed until next call of loadSetting
QGraphicsRectItem : legend, position relative to bg is fixed throughout app
QGraphicsEllipseItem : region centers
I want the map to behave as follow:
no scrollbars to be displayed, and the background image fillup all the visible area of the view/scene.
when the widget is re-sized, the QGraphics*Items will re-size themselves accordingly (as if the view is zoomed)
relative positions of QGraphicsEllipseItems, remain fixed until next call of loadSetting()
Now I have problem in getting the background image displayed properly.
Constructor [I'm adding this view to a QTabWidget directly: myTab->addTab("name", my_view_); ]
MyView::MyView(QWidget *parent) : QGraphicsView(parent) {
bg_pixmap_ = new QGraphicsPixmapItem();
legend_ = new MapLegend();
setScene(new QGraphicsScene(this));
scene()->addItem(bg_pixmap_);
scene()->addItem(legend_);
}
Load map setting (during program execution, this method may be invoked multiple times)
void MyView::loadSetting(Config* cfg) {
if (!cfg) return;
/* (a) */
scene()->clearFocus();
scene()->clearSelection();
for (int i = 0; i < symbols_.size(); i++)
scene()->removeItem(symbols_[i]);
qDeleteAll(symbols_);
symbols_.clear();
/* (a) */
/* (b) */
background_ = QPixmap(QString::fromStdString(cfg->district_map));
bg_pixmap_->setPixmap(background_);
for (size_t i = 0; i < cfg->centers.size(); i++) {
qreal x = cfg->centers[i].first * background_.width();
qreal y = cfg->centers[i].second * background_.height();
MapSymbol* item = new MapSymbol(x, y, 10);
symbols_.append(item);
scene()->addItem(item);
}
/* (b) */
update();
}
Questions
Now all items except the 'bg_pixmap_' got displayed, and I checked the 'background_' variable that it loads the image correctly. Is there anything I missed?
How do I implement the resizeEvent of MyView to cope with the desired 'resize-strategy'?
Related
I am trying to use the scale(qreal x, qreal y) method/function for Graphics view to scale a pixmap in the graphics view widget. Below I've attached code of my attempts. When I execute the program it will display my pixmap but as soon as I move the horizontal slider the pixmap disappears and the graphics view just displays a blank white page. The commented out parts are all things I have tried but produced the same result. I'm not entirely sure if scaling the graphics view will scale everything in the graphics view, I assumed so but could not find anything concrete from the documentation.
*One thing to note is that I have a button that displays two different Pixmaps, even after I am presented with the white screen upon moving the scroll bar, if I press the button it will still update the y axis scroll bar(as one pixmap is slightly larger than the graphics widget) however a blank white graphics view is still displayed
*PixMapView is the name of the graphics view widget
void CanvasTest::on_horizontalSlider_valueChanged(int value)
{
//int scaleX = value/(ui->horizontalSlider->maximum())*2;
//Graph is updating and Y scroll bar is updating to show for it
//int scaleY = ui->verticalSlider->value();
QGraphicsScene* scene = ui->PixMapView->scene();
ui->PixMapView->scale(value/10, 1);
ui->PixMapView->setScene(scene);
ui->PixMapView->show();
}
There was truncation issue using integers, this code also uses static variables to keep track of the previous scale values.
static float valueTracker = 1;\
static float valueTracker1 = 1;
static int count = 1;
bool order;
if (count%2 == 1)
{
valueTracker = newSliderValue;
order = 0;
}
else
{
valueTracker1 = newSliderValue;
order = 1;
}
if(valueTracker == valueTracker1 || valueTracker == 0 || valueTracker1 == 0)
{
count++;
return;
}
else if(order == 0)
{
ui->PixMapView->scale(((valueTracker/valueTracker1)), 1);
}
else if(order == 1)
{
ui->PixMapView->scale(((valueTracker1/valueTracker)), 1);
}
count++;
I am trying to create a ground tile that, once is off screen moves to the forward position in front of the other ground tile that is currently in the screen.
I have barely tried anything in code that would be even slightly useful to add to this question. Could someone point me in the right direction to be able to get this done so I don't have to just duplicate hundreds of tiles?
Thanks!
Attach this scrip on your Tileobject.
using UnityEngine;
public class SpawnTiles : MonoBehaviour {
private Material currentTile;
public float speed;
private float offset;
// Use this for initialization
void Start () {
currentTile = GetComponent<Renderer>().material;
}
// Update is called once per frame
void Update () {
offset += 0.001f;
currentTile.SetTextureOffset ("_MainTex", new Vector2 (offset * speed, 0));
}
}
Edit
This is what you want?
If YES, follow theses steps.
Create > 3D Object > Quad (Resize as you want)
Select your tile sprite:
Texture type = texture
Wrap mode = repeat
Now creat new Material: Create > Material
Select: Shader = Unlit/Texture
Texture select your previous texture.
Drag and drop this Material inside Quadobject.
Adjust tiles at inspector.
Result
Creat new scrip SpawnTiles and attach at Quadobject.
using UnityEngine;
public class SpawnTiles : MonoBehaviour {
private Material currentTile;
public float speed;
private float offset;
// Update is called once per frame
void Update () {
GetComponent<Renderer>().material.mainTextureOffset = new Vector2 (Time.time * speed, 0f);
}
}
Ajust tiles movement speed at inspector.
Finish rename Quadobject as you want.
If you want to only move the back tile to the front, you probably don't need it, but I still highly suggest looking into object pooling.
To detect if a camera can't see the tile, use this: Renderer.isVisible
To move the tile, if all the tiles are the same dimensions, you could just increase it's position.x by the amount you need.
I have found one solution using WorldPointToViewport().
Here is my script:
using UnityEngine;
using System.Collections;
public class groundTilingScript : MonoBehaviour {
Transform ground; //For reference to the transform
Camera cam; //Reference to Main Camera
float groundWidth; //The width of the transform, used for calculating current max x position of transform and next placement x position
private float nextXPos = 0.0f; //Store next x position in variable for easier reading
// Use this for initialization
void Start () {
//Set up References
ground = transform;
cam = Camera.main;
//Store Ground width (Width of the ground tile)
groundWidth = ground.GetComponent<Renderer> ().bounds.size.x;
}
// Update is called once per frame
void Update () {
//Create new Vector3 to be used in WorldToViewportPoint so it doesn't use the middle of the ground as reference
Vector3 boxRightPos = new Vector3 (ground.position.x + groundWidth/2, ground.position.y, ground.position.z);
//Store view Position of ground
Vector3 viewPos = cam.WorldToViewportPoint (boxRightPos);
//If the ground tile is left of camera viewport
if (viewPos.x < 0) {
//gameObject is offscreen, destroy it and re-instantiate it at new xPosition
float currentRightX = ground.position.x + groundWidth;
nextXPos = currentRightX + groundWidth;
Instantiate (gameObject, new Vector3 (nextXPos, ground.position.y, ground.position.z), ground.rotation);
Destroy (gameObject);
}
}
}
NOTE: I have to set up two ground tiles initially to give room for camera to go further than the ground tile. (One tile on screen, one off)
Again, this is just my attempt. I am completely open to criticism.
I'm implementing an image viewer on an embedded platform. The hardware is a sort of tablet and has a touch screen as input device. The Qt version I'm using is 5.4.3.
The QGraphicsView is used to display a QGraphicsScene which contains a QGraphicsPixmapItem. The QGraphicsPixmapItem containts the pixmap to display.
The relevant part of the code is the following:
void MyGraphicsView::pinchTriggered(QPinchGesture *gesture)
{
QPinchGesture::ChangeFlags changeFlags = gesture->changeFlags();
if (changeFlags & QPinchGesture::ScaleFactorChanged) {
currentStepScaleFactor = gesture->totalScaleFactor();
}
if (gesture->state() == Qt::GestureFinished) {
scaleFactor *= currentStepScaleFactor;
currentStepScaleFactor = 1;
return;
}
// Compute the scale factor based on the current pinch level
qreal sxy = scaleFactor * currentStepScaleFactor;
// Get the pointer to the currently displayed picture
QList<QGraphicsItem *> listOfItems = items();
QGraphicsItem* item = listOfItems.at(0);
// Scale the picture
item.setScale(sxy);
// Adapt the scene to the scaled picture
setSceneRect(scene()->itemsBoundingRect());
}
As result of the pinch, the pixmap is scaled starting from the top-left corner of the view.
How to scale the pixmap respect to the center of the QPinchGesture?
From The Docs
The item is scaled around its transform origin point, which by default is (0, 0). You can select a different transformation origin by calling setTransformOriginPoint().
That function takes in a QPoint so you would need to find out your centre point first then set the origin point.
void QGraphicsItem::setTransformOriginPoint(const QPointF & origin)
I have created a QGraphicsScene scene and added some graphcis items (lines, rectangles) etc to the scene.
I can loop through them using this list :
QList<QGraphicsItem*> all = items();
I enabled movement for these items and I am able to drag them by click selecting them. But after an element has been dragged, it stops showing up in the call to items() function of the QGraphicsScene.
QList<QGraphicsItem*> all = items();
None of the dragged items show up in the above list, while non-dragged ones do show up.
Does dragging the QGraphicScene elements change their parent ? or any other reason somebody could suggest for such an issue ?
{P.S. Code is too very big to share}
Edit 1 :
I am using the flags QGraphicsItem::ItemIsSelectable and QGraphicsItem::ItemIsMovable for making the items movable.
foreach(QGraphicsItem* itemInVisualScene, items())
{
itemInVisualScene->setFlag(QGraphicsItem::ItemIsSelectable, itemsMovable);
itemInVisualScene->setFlag(QGraphicsItem::ItemIsMovable, itemsMovable);
}
By default I add few rectangle to the scene. Then in the 'move mode' I drag them around. Then in the 'add mode' I click on screen to add new rectangles. I have written a logic to check if I am clicking on any existing drawn rectangle :
void Scene::mousePressEvent(QGraphicsSceneMouseEvent * event)
{
if(eDrawLines == sceneMode)
{
dragBeginPoint = event->scenePos();
dragEndPoint = dragBeginPoint;
QList<QGraphicsItem*> all = items();
for (int i = 0; i < all.size(); i++)
{
QGraphicsItem *gi = all[i];
// Clicked point lies inside existing rect
if( QGraphicsRectItem::Type == gi->type() && gi->contains(dragBeginPoint))
{
std::cout << "Pressed inside existing rect" << std::endl;
return;
}
}
std::cout << "Point not found, add new rectangle" << std::endl;
}
QGraphicsScene::mousePressEvent(event);
}
This adding of rectangles work fine for rects which were not dragged in the 'move mode'. But rects which were moved do not seem to recognize the click anymore. My control comes out of the loop even when I click on an existing rectangle which was dragged earlier.
QGraphicsItem's transform is changed after dragging and therefore need to transform the point to item's local coordinates.
gi->contains(gi->mapFromScene(dragBeginPoint))
To convert or get item's position in scene coordinates, use
gi->mapToScene(0,0) or gi->scenePos()
I have a QSqlTableModel model that contains my data.
I have made a QGraphicsScene scene and a QGraphicsView view so the user can move around same myQGraphicsTextItem text items until the desired position.
Something like this:
myQWidget::myQWidget()
{
//these are member of my class
chequeScene = new QGraphicsScene();
chequeView = new QGraphicsView();
model = new QSQLTableModel();
//populate model, inialize things here...
//add predefined items to the scene
setScene();
}
there's a button to show the view and move the textitems of scene. It works well.
there's a button that calls the slot print that belongs to the class. It configures a QPrinter and then calls the following paint method myQWidget::paint(), after that scene->render() is called.
The porpoise of the method below is to print data on a paper that is configured to have the same size than the scene while printing the data in the same relative position the textItem had on the scene. Can't do it with QList it doesn't order the items in the same way I added them to the scene.
Here is my code below, it prints with overlapping of some fields doe to QList order items as they appear on the scene.
void myQWidget::paint()
{
qreal dx = 0;
qreal dy = 0;
QList<QGraphicsItem*> L = chequeScene->items();
for (int j=0; j<model->columnCount(); j++) {
if(!L.isEmpty())
{
//Saves the position on dx, dy
dx = L.first()->scenePos().x();
dy = L.first()->scenePos().y();
chequeScene->removeItem( L.first() );
delete L.first();
L.removeFirst();
}
QString txt("");
//selecting printing formar for each column
switch(j)
{
case COLUMNADEFECHA:
txt = QDate::fromString(model->data(model->index(chequenum,j)).toString(), "yyyy/MM/dd").toString("dd/MM/yyyy");
break;
case COLUMNADECHEQUES:
break;
default:
txt = model->data(model->index(chequenum,j)).toString();
break;
}
//filtering not important columns
if(j!=COLUMNADECHEQUES)
{
//Supposubly item with the desired information is added to the scene
//on the same position it had before. Not working.
GraphicsTextItem *item=new GraphicsTextItem();
item->setPlainText(txt);
item->setPos(dx,dy);
chequeScene->addItem(item);
}
}
}
Any idea on how to get this working?
I think as you are getting the scenePos in dx and dy but are setting it using setPos function.
Also as you are using your GraphicsTextItem and not QGraphicsTextItem maybe a look at your paint method will help in understanding the problem.
Try using item->mapFromScene(dx, dy) and then use those coordinates to set the item position by item->setPos(..).
Hope This Helps..