Qt: setScreenRect = segfault - c++

Basically I need something to draw on it,
that is simple to use with designer (for example inherit from QWidget and override of paintEvent require some efforts to use it in Qt designer).
So I add QGraphicsView to .ui file and write such code in button method:
QGraphicsScene *scene = ui->graphicsView->scene();
const QRectF scene_r = ui->graphicsView->sceneRect();
//here I see that scene_r == {0, 0, 0, 0};
then I add such code:
const QSize draw_size = ui->graphicsView->size();
//draw_size == {100, 100}
scene->setSceneRect(QRectF(0, 0, draw_size.width(), draw_size.height()));
and got segfault on line scene->setSceneRect what is going on here?
Actually I want right such code:
//scene size == draw_size
QPixmap pix(draw_size.width(), draw_size.height());
//fill pix with external program
scene->addPixmap(map_pix);
is it possible?
I never before work with QGraphicsView.

The reason you get a segfault is because you haven't set any scene for the view, hence the scene() will return a null pointer.
QGraphicsScene scene;
QGraphicsView view(&scene);
view.show();
Alternative is to create the view without a scene then add it later:
void setScene(QGraphicsScene *scene)
Reference:
http://doc.qt.io/qt-5/qgraphicsview.html

Related

How to resize QWidget added in QGraphicScene through QGraphicsProxy?

I have added a widget to a graphic scene (QGraphicScene) through a QGraphicsProxyWidget. To move and select the widget added QGraphicsRectItem handle.
To resize widget added QSizegrip to widget. But when i resize widget more than the QGraphicsRect item rect right and bottom edges goes behind .How to overcome this problem?
When i resize widget graphics rect item should resize or vice-versa should happen. how to do this? Any other ideas are welcome.
Here is the code
auto *dial= new QDial(); // The widget
auto *handle = new QGraphicsRectItem(QRect(0, 0, 120, 120)); // Created to move and select on scene
auto *proxy = new QGraphicsProxyWidget(handle); // Adding the widget through the proxy
dial->setGeometry(0, 0, 100, 100);
dial->move(10, 10);
proxy->setWidget(dial);
QSizeGrip * sizeGrip = new QSizeGrip(dial);
QHBoxLayout *layout = new QHBoxLayout(dial);
layout->setContentsMargins(0, 0, 0, 0);
layout->addWidget(sizeGrip, 0, Qt::AlignRight | Qt::AlignBottom);
handle->setPen(QPen(Qt::transparent));
handle->setBrush(Qt::gray);
handle->setFlags(QGraphicsItem::ItemIsMovable |
QGraphicsItem::ItemIsSelectable);
Scene->addItem(handle); // adding to scene
Here is the Output::
Before Resize
After Resize
Cause
The QGraphicsRectItem, which you use as a handle, is not aware of the size changes of QDial, so it does not respond by resizing itself.
Limitation
QWidget and its subclases do not provide something like a sizeChanged signal out of the box.
Solution
Considering the cause and the given limitation, my solution would be the following:
In a subcalss of QDial, say Dial, add a new signal void sizeChanged();
Reimplement the resizeEvent of Dial like this:
in dial.cpp
void Dial::resizeEvent(QResizeEvent *event)
{
QDial::resizeEvent(event);
sizeChanged();
}
Change auto *dial= new QDial(); to auto *dial= new Dial();
Add the following code after Scene->addItem(handle); // adding to scene:
in the place, where your example code is
connect(dial, &Dial::sizeChanged, [dial, handle](){
handle->setRect(dial->geometry().adjusted(-10, -10, 10, 10));
});
Note: This could be also solved using eventFilter instead of subclassing QDial. However, from your other question I know that you already subclass QDial, that is why I find the proposed solution more suitable for you.
Result
This is the result of the proposed solution:

adding a custom widget in Layout at execution

I'm under Ubuntu 18.04 and using last QtCreator with last Qt5 framework
I'm trying to setup a vertical layout with at top an horizontal nested layout and under a custom made widget (based on clock exemple for the moment)
I setup a fresh widget project but as I dont understand yet how to get acess to nested layout from c++ code I removed automaticaly created mainform and created layout at execution.
If I use my custom widget as window it works if I use a window and add my custom widget it works but if I add a layout, add my custom widget to this layout and call setLayout on window it disappear...
I tried almost all orders : set the layout first or after adding my widget.
I tried to call show() on my widget or not befor or after adding it to layout
I tried to add the nested layer first or last nothing change
I 've read several time exemples and manual about layout and nested one
I can see my nested layout but not my widget
here's my main :
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget w;
w.setWindowTitle("WOUND : Windings Organiser with Usefull and Neat Drawings");
QVBoxLayout* hl=new QVBoxLayout;// top vertical layout
QHBoxLayout* slotqueryLayout=new QHBoxLayout; // nested first horizontal layout
QLabel *slotqueryLabel = new QLabel("Slot number:");
QLineEdit *slotqueryEdit = new QLineEdit("48");
slotqueryLayout->addWidget(slotqueryLabel);
slotqueryLayout->addWidget(slotqueryEdit);
hl->addLayout(slotqueryLayout);
WindingViewer* wv=new WindingViewer(&w); // my widget is just a simple canvas to draw things
hl->addWidget(wv);
wv->show(); // dont know if it's needed but if I remove it it dont change anything / tried to do it before or after adding to layout
w.setLayout(hl); // if called before adding content it dont change
w.show();
return a.exec();
}
and here you can find my custom widget:
class WindingViewer : public QWidget
{
Q_OBJECT
public:
explicit WindingViewer(QWidget *parent = nullptr);
protected:
void paintEvent(QPaintEvent *event) override;
signals:
public :
int SlotNumber;
public slots:
};
and
WindingViewer::WindingViewer(QWidget *parent) : QWidget(parent)
{
SlotNumber=3;
resize(200, 200);
}
void WindingViewer::paintEvent(QPaintEvent *)
{
int side = qMin(width(), height());
QColor SlotColor(127, 127, 127);
QPainter painter(this);
static const QPoint slotpolygonext[4] = {
QPoint(-2,85),
QPoint(-3,95),
QPoint(3, 95),
QPoint(2, 85)
};
static const QPoint slotpolygonint[5] = {
QPoint(-1,75),
QPoint(-2,85),
QPoint(2, 85),
QPoint(1, 75),
QPoint(-1,75),
};
painter.setRenderHint(QPainter::Antialiasing);
painter.translate(width() / 2, height() / 2);
painter.scale(side / 200.0, side / 200.0);
painter.setPen(SlotColor);
for (int i = 0; i < SlotNumber; ++i) {
painter.drawPolyline(slotpolygonext,4);
painter.drawPolyline(slotpolygonint,5);
painter.rotate(360.0/SlotNumber);
}
}
I hope the question is clear enough. I've search for an answer here and over internet before posting. I found few things but nothing totaly related.
The custom widget is part of the window, you could see if manually with the mouse you make the height increase.
And then why is it hidden?
The layouts handle size policies and use the sizeHint() function of the widgets to obtain the default size, and in your case the sizeHint() is not implemented because it is not observed when the window is displayed, the solution is to implement that method:
*.h
public:
explicit WindingViewer(QWidget *parent = nullptr);
QSize sizeHint() const override;
*.cpp
QSize WindingViewer::sizeHint() const
{
return QSize(200, 200);
}

qt remove layouts code

I have less than 1 day of experience in QT (that's why I do not know much of it) I have a window full of information (labels, text, buttons, etc) organized by layouts.
I need that after I press one button, all of the components in a window be hidden (which I already did) except for one label which should increase to barely the size of the whole window
Despite I tried modifying the "geometry" attribute (with code) the hidden layouts do not let the label to be increased. I thought also of using the option of layout breaking, but the label losses its dynamism. Could anyone please recommend me anything to do? Thanks.
Has anyone done something like this before. Thanks.
I once provided an answer to SO: Qt - How to create Image that scale with window, and keeps aspect ratio?. The actual intention was to scale an image in a QLabel with original aspect ratio to consume maximum available size.
However, I got the feedback that the suggested solution would not work properly when my Label would be used in a QGridLayout. (This sounds very similar to the issue of the OP.) Hence, I modified the sample to reproduce the issue and fiddled a little bit around with. For me, it seems that resize events of the main window are processed in the QGridLayout but affect layouted image label only partially. (Shrinking is applied but growing not.) Fortunately, I found a very simple work-around: Setting a non-empty frame to the QLabel solved the problem. I had a look into the source code on woboq.org. I hoped to get a hint what the changed frame style would activate (to apply this as fix for my resize issue). Finally, I was not patient enough and put it aside.
Beside of this QLabel in a QGridLayout resize issue, changing the visibility of widgets should cause a proper re-layout. I would prefer show/hide (instead of delete and re-new) as this is surely easier to implement, more efficient, and less error-prone.
I took the old sample code and added a tool button which can be used to toggle the visibilty of some of the layouted widgets:
// Qt header:
#include <QtWidgets>
class LabelImage: public QLabel {
private:
QPixmap _qPixmap, _qPixmapScaled;
public:
void setPixmap(const QPixmap &qPixmap) { setPixmap(qPixmap, size()); }
protected:
virtual void resizeEvent(QResizeEvent *pQEvent);
private:
void setPixmap(const QPixmap &qPixmap, const QSize &size);
};
void LabelImage::resizeEvent(QResizeEvent *pQEvent)
{
QLabel::resizeEvent(pQEvent);
setPixmap(_qPixmap, pQEvent->size());
}
void LabelImage::setPixmap(const QPixmap &qPixmap, const QSize &size)
{
_qPixmap = qPixmap;
_qPixmapScaled = _qPixmap.scaled(size, Qt::KeepAspectRatio);
QLabel::setPixmap(_qPixmapScaled);
}
int main(int argc, char **argv)
{
qDebug() << "Qt Version:" << QT_VERSION_STR;
// main application
QApplication app(argc, argv);
// setup GUI
QMainWindow qWin;
QToolBar qToolbar;
QAction qCmdTgl(QString::fromUtf8("Decoration"));
qCmdTgl.setCheckable(true);
qCmdTgl.setChecked(true);
qToolbar.addAction(&qCmdTgl);
qWin.addToolBar(&qToolbar);
QGroupBox qBox;
QGridLayout qGrid;
// a macro for the keyboard lazy:
#define Q_LBL_WITH_POS(ROW, COL) \
QLabel qLbl##ROW##COL(QString::fromLatin1(#ROW", "#COL)); \
/*qLbl##ROW##COL.setFrameStyle(QLabel::Raised | QLabel::Box);*/ \
qGrid.addWidget(&qLbl##ROW##COL, ROW, COL, Qt::AlignCenter)
Q_LBL_WITH_POS(0, 0);
Q_LBL_WITH_POS(0, 1);
Q_LBL_WITH_POS(0, 2);
Q_LBL_WITH_POS(1, 0);
LabelImage qLblImg;
qLblImg.setFrameStyle(QLabel::Raised | QLabel::Box);
qLblImg.setAlignment(Qt::AlignCenter);
//qLblImg.setMinimumSize(QSize(1, 1)); // seems to be not necessary
qLblImg.setSizePolicy(
QSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored));
QPixmap qPM;
if (qPM.load("cats.jpg")) qLblImg.setPixmap(qPM);
else {
qLblImg.setText(
QString::fromLatin1("Sorry. Cannot find file 'cats.jpg'."));
}
qGrid.addWidget(&qLblImg, 1, 1, Qt::AlignCenter);
qGrid.setRowStretch(1, 1); // tell QGridLayout to stretch this cell...
qGrid.setColumnStretch(1, 1); // ...prior to other cells (w/ stretch 0)
Q_LBL_WITH_POS(1, 2);
Q_LBL_WITH_POS(2, 0);
Q_LBL_WITH_POS(2, 1);
Q_LBL_WITH_POS(2, 2);
qBox.setLayout(&qGrid);
qWin.setCentralWidget(&qBox);
qWin.show();
// install signal handlers
QObject::connect(&qCmdTgl, &QAction::triggered,
[&](bool on) {
qLbl00.setVisible(on); qLbl01.setVisible(on); qLbl02.setVisible(on);
qLbl10.setVisible(on); qLbl12.setVisible(on);
qLbl20.setVisible(on); qLbl21.setVisible(on); qLbl22.setVisible(on);
});
// run application
return app.exec();
}
I compiled and tested in VS2013 on Windows 10:
After toggling the Decoration tool button:
Note:
Out of curiosity, I commented the line which changes the frame style
qLblImg.setFrameStyle(QLabel::Raised | QLabel::Box);
and again, resizing of image didn't work properly anymore.
You can remove and hide widgets inside a layout using QLayout::removeWidget(*widget); but you do not need to actually remove it. You should use QWidget::hide() for the content to disappear and for the video label's cell to be able to take that space. I think you need to pay attention to the video label's size policy if it does not increase in size. Assuming you have a QGridLayout like so:
label1 label2 label3
label4 videoLabel label5
button1 button2 button3
And let's say, when you click button3, label1, label2 and label4 should all disappear and videoLabel takes the newly created space. I would group the widgets label1, label2, label4 and videoLabel into a single widget having its own sub-layout. I use QSizePolicy::Expaning to make sure my videoLabel takes the maximum space possible. Here is the implementation:
Widget::Widget(QWidget *parent) :
QWidget(parent)
{
setStyleSheet("QLabel{font-size:20px;}");
fullScreen = false; //current fullscreen state
//main grid layout
baseLayout = new QGridLayout(this);
baseLayout->setMargin(0);
baseLayout->setAlignment(Qt::AlignCenter);
setLayout(baseLayout);
//widget container for label1, label2, label4, videolabel
groupWidget = new QWidget();
//sub-layout inside the group layout
subLayout = new QGridLayout();
subLayout->setAlignment(Qt::AlignCenter);
subLayout->setMargin(0);
groupWidget->setLayout(subLayout);
//label and button instantializing. I set background colors to show their sizes
label1 = new QLabel("Label1");
label1->setStyleSheet("background-color:white;");
label2 = new QLabel("Label2");
label2->setStyleSheet("background-color:orange;");
label3 = new QLabel("Label3");
label4 = new QLabel("Label4");
label4->setStyleSheet("background-color:blue;color:white;");
label5 = new QLabel("Label5");
videoLabel = new QLabel("videoLabel");
videoLabel->setStyleSheet("background-color:red;");
videoLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
button1 = new QPushButton("button1");
button2 = new QPushButton("button2");
button3 = new QPushButton("button3");
//the grouped widget spans for 2 rows and columns, hence "2,2"
baseLayout->addWidget(groupWidget, 0,0,2,2);
subLayout->addWidget(label1, 0, 0);
subLayout->addWidget(label2, 0, 1);
subLayout->addWidget(label4, 1, 0);
subLayout->addWidget(videoLabel, 1, 1);
//adding rest of the labels and buttons to the base grid
baseLayout->addWidget(label3, 0, 2);
baseLayout->addWidget(label5, 1, 2);
baseLayout->addWidget(button1, 2, 0);
baseLayout->addWidget(button2, 2, 1);
baseLayout->addWidget(button3, 2, 2);
//button3 toggles fullscreen
connect(button3, SIGNAL(clicked(bool)), this, SLOT(onButton3Clicked(bool)));
}
//slot for button3 click
void Widget::onButton3Clicked(bool)
{
if (!fullScreen){
//removing widget from layouts is not really necessary. Make sure to hide
/*subLayout->removeWidget(label1);
subLayout->removeWidget(label2);
subLayout->removeWidget(label4);*/
label1->hide();
label2->hide();
label4->hide();
fullScreen = true;
}
else{
label1->show();
label2->show();
label4->show();
/*subLayout->addWidget(label1, 0, 0);
subLayout->addWidget(label2, 0, 1);
subLayout->addWidget(label4, 1, 0);*/
fullScreen = false;
}
}
I got the following results for this:
Keep in mind there are other approaches to this question. This one need not be necessarily the best when it comes to memory, but it is quite easy to follow.

Change Pixmap Position in QGraphicsScene/View in Qt5

I have a normal QGraphicsView/QGraphicsScene and all I want to do is load a QPixmap (.png) to the graphic and manually set the position of that QPixmap image. I've found solutions but they don't work on Qt5. Any ideas on how to achieve this on Qt5? Thank you.
QGraphicsScene* scene = new QGraphicsScene(QRect(0, 0, 600, 400));
QPixmap Pix(":/test.gif");
// doesnt work
//Pix.setGeometry(QRect(-30, 40, 260, 200));
QGraphicsPixmapItem *item1 = scene->addPixmap(Pix);
// doesnt work
//item1->setPos(-25, 45);
//scene->addPixmap(Pix)->setPos(0,0);
//QGraphicsView* view = new QGraphicsView(ui->centralWidget);
QGraphicsView* view = new QGraphicsView(this);
view->setScene(scene);
You can browse the image from your computer and set its position.
Just in case, It helps someone.
QString fileNamez = QFileDialog::getOpenFileName(this,"Open Filezzz","C:/");
QGraphicsPixmapItem *pm = scene->addPixmap( QPixmap(fileNamez) );
pm->setPos(xPos,yPos);
If you use a QGraphicsPixmapItem in your implementation, or indeed any Qt object, you need to include it in the cpp: -
#include <QGraphicsPixmapItem>

QGraphicsView possible bug?

The example code is from my project. I've tried to make it as short as possible and to the point.
The overlay is used to draw over all the other widgets in the app. This works for most widgets, but today I've started to notice that QAbstractScrollArea subclasses are giving me a hard time. The problem is that the overlay appears not on top, and whatever drawing that happens is blocked.
#include <QtGui/QApplication>
#include <QtGui/QVBoxLayout>
#include <QtGui/QGraphicsView>
#include <QtGui/QPushButton>
class View : public QGraphicsView{
public:
View(){
//delete viewport(); setViewport(new QWidget);
}
};
class Widget : public QWidget{
QWidget* overlay_;
public:
Widget(){
resize(512, 512);
QVBoxLayout* layout = new QVBoxLayout;
QPushButton* button = new QPushButton(" Click Me! ");
layout->addWidget(button);
layout->addWidget(new View);
overlay_ = new QWidget(this);
overlay_->installEventFilter(this);
connect(button, SIGNAL(clicked()),
overlay_, SLOT(show()));
overlay_->hide();
setLayout(layout);
}
bool eventFilter(QObject* target, QEvent* event){
if(target == overlay_){
if(event->type() == QEvent::Paint && overlay_->isVisible()){
overlay_->resize(size());
QPainter painter(overlay_);
painter.setPen(QPen(QColor(1, 102, 192, 255), 1, Qt::SolidLine,
Qt::FlatCap, Qt::MiterJoin));
painter.drawRect(rect().adjusted(60, 0, -60, 0));
return true;
}
}
}
};
int main(int argc, char *argv[]){
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
To fix this in this example and have overlay go on top of View, you'll need to uncomment the commented line at the top. So my question is this: why do I need to delete and assign a new viewport widget in the constructor in order for overlay not get overdrawn?
This isn't a bug with QGraphicsView, it will happen if you use a standard QScrollArea as well.
The issue, I think, is the order in which Qt draws child widgets. Sibling widgets are drawn in the order they are added to the parent (although you can't rely on this).
The reason that resetting the viewport "solved" the problem is because when you do that you create a new QWidget that has no background to be the viewport. The QGraphicsView is still being drawn over the overlay_, it just has a transparent viewport. Notice how it's still drawn behind the pushbutton, however.
If you want to draw an overlay only over the QGraphicsView, you can override QGraphicsView::paintEvent() and do it there. If you want to draw the overlay over your entire widget, I would embed your layout inside a second QWidget and then try using QWidget::raise() to force the overlay visually to the top.