(Qt) Rendering scene, different items in the same relative positions - qt

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..

Related

Adding Rows in a QTreeWidget in runtime messes up widgetItems visuals

I have a QDialog show a QTreeWidget that has the parameters of some objects.
I have added a button to add extra fields in the vectors of the objects visually like this.
void on_Create_Surface_Pressed()
{
QPushButton * const button = qobject_cast<QPushButton*>(sender());
QTreeWidgetItem* branch = treeButtons[button];
if(branch)
{
QTreeWidgetItem* leaf = new QTreeWidgetItem(branch);
QString str("Point ");
str+=QString::number(branch->childCount()-1);
QLabel* label = new QLabel(str);
QString surfType[3] = {QString("x") , QString("y") ,QString("z")};
QTableWidget* surfTable = sampleTree( surfType);<--(Create and add a
Table under the
qtreewidgetItem)
leaf->treeWidget()->setItemWidget(leaf , 0 , label);
leaf->treeWidget()->setItemWidget(leaf , 1 , surfTable);
update();
}
}
My problem is that the new rows are rendered above the next QTreeWidgetItem until the user collapses the tree(which is the gimmick i m using).
Is there a workaround for this? Or isn't QTreeWidget purposed for this use and a QTreeView would serve better?

Printing QGraphicsScene cuts objects in half

I want to print everything what's on QGraphicsScene:
void MainWindow::on_print_clicked()
{
if (template_ptr != Q_NULLPTR) {
QPrinter printer(QPrinter::HighResolution);
if (QPrintDialog(&printer, this).exec() == QDialog::Accepted) {
if (QPageSetupDialog(&printer, this).exec() == QDialog::Accepted) {
QPainter painter(&printer);
painter.setRenderHint(QPainter::Antialiasing);
painter.setRenderHint(QPainter::TextAntialiasing);
qreal x, _y, h, w, fake;
ui->graphicsView->sceneRect().getRect(&x, &_y, &w, &fake);
h = template_ptr->page_height*2.0;
qint32 page = 0;
while (true) {
qreal y = _y + h*page;
QRectF leftRect(x, y, w, template_ptr->page_height*2.0*template_ptr->max_pages - h*page);
if (ui->graphicsView->scene()->items(leftRect).length() <= 0) {
break;
}
QRectF sourceRect(x, y, w, h);
ui->graphicsView->scene()->render(&painter, printer.pageRect(), sourceRect);
printer.newPage();
page++;
}
}
}
}
}
That's the effect (PDF file):
Every point on the lists is a single QGraphicsItem and I don't know what's the easiest way to move the items that doesn't fit within a page, to the next page... I probably could do some error-prone mathematics to achieve that but I'm pretty sure this can be resolved in some elegant way.
What I would do...
Step 1: I would first create a copy of the scene (a new QGraphicsScene with the same size as your original) and move all items there.
Step 2: Create a temporary scene for each new page, with a sceneRect equal to the section you wish to print.
Step 3: Move to it the items from the scene copy, that are contained in the sceneRect of the temp scene.
Step 4: After printing, move the printed items to the original scene...
Step 5: Shorten your copy scene bounding rect to the bounding rect of the items still left inside it. (to allow step 4 to place items exactly in place, change the x/y coordinates as well as change the w/h)
Repeat steps 3 to 5 till the copy scene is empty.

Dragged QGraphicsItem not visible in items() function

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()

Displaying image as background of QGraphicsScene

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'?

Drawing lines and checkbox on same layer in Qt

I want to design a GUI using Qt. That contains lines and check-boxs, which are connected to each other like this :
----------[ ]-----------
------[ ]---------[ ]-------------
(where dash represents line and [] is for check-box)
Lines are created dynamically. And selecting the check-box will disable the corresponding line. So basically the lines and check-box should be on same layer.
Any hint/link about the implementation is appreciated.
You'll need a combination of QFrame, QCheckBox, and QHBoxLayout. For something a little fancier, you could sub-class your own QWidget for each section and add them incrementally to a QVBoxLayout. Something like this...
class CheckLine : public QWidget
{
Q_OBJECT
public:
CheckLine(int numboxes = 1, QObject* parent = 0) :
QWidget(parent)
{
m_layout = new QHBoxLayout;
m_layout->setSpacing(0); //you can also set the margins to zero if need be
setLayout(m_layout);
QFrame* firstline = new QFrame();
firstline->setFrameShape(QFrame::HLine);
m_layout->addWidget(firstline);
m_lines.append(firstline);
for(int i = 0; i < numboxes; ++i)
addBox();
}
void addBox()
{
QCheckBox* newbox = new QCheckBox(""); //add text here - or leave it blank if you want no label
m_newbox->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
m_layout->addWidget(newbox);
m_boxes.append(newbox);
QFrame* newline = new QFrame();
newline->setFrameShape(QFrame::HLine);
m_layout->addWidget(newline);
m_lines.append(newline);
/* link each checkbox to disable the line after it */
connect(newbox, SIGNAL(toggled(bool)), newline, SLOT(setEnabled(bool)));
// connect(newbox, SIGNAL(toggled(bool)), this, SLOT(setEnabled(bool))); //use this instead if you want it to disable the entire row
}
private:
QHBoxLayout* m_layout;
QList<QCheckBox*> m_boxes;
QList<QFrame*> m_lines;
};
Then, create a widget with a QVBoxLayout and new a CheckLine, incrementing numboxes by 1 each time. Tweak the code if you want any checkbox to disable the entire line.

Resources