FLTK draw pixmap gives segfault - c++

I'm trying to draw a xpm file in a C++ program with FLTK.
Here's the code
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include "image.xpm"
#include <FL/Fl_Pixmap.H>
#include <FL/fl_draw.H>
#include <FL/Fl_Image.H>
int main(int argc, char ** argv)
{
Fl_Window *window = new Fl_Window(800,650);
Fl_Pixmap pix(XFACE);
pix.draw(200,200);
window->end();
window->show(argc,argv);
return Fl::run();
}
XFACE is a valid xpm object inside "image.xpm"
But I'm getting a segmentation fault at the pix.draw() line.
What causes this?

/* Try this - this works for me, and I guess is what you meant! */
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Pixmap.H>
#include "image.xpm"
int main(int argc, char ** argv)
{
Fl_Window *window = new Fl_Window(800,650);
Fl_Box *image_box = new Fl_Box(5, 5, 790, 640);
Fl_Pixmap pix(XFACE);
window->end();
image_box->image(pix);
window->show(argc,argv);
return Fl::run();
}
/* end of file */

To be honest, that doesn't even look like valid fltk code; you are calling the draw() method directly, and AFAIK that is seldom valid in fltk.
You probably want to ask over on their mailing list - they are pretty responsive.
Also, did you look at the pixmap demo in the "test" folder of the tarball - see what it does, then copy it!

Related

running draw_polygon example in CGAl package in qt widget application

I try to following CGAL example in Qt widget application :
example
main.ccp:
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
mainwindow.ccp :
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Polyhedron_3.h>
#include <CGAL/IO/Polyhedron_iostream.h>
#include <CGAL/draw_polyhedron.h>
#include <fstream>
typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;
typedef CGAL::Polyhedron_3<Kernel> Polyhedron;
void MainWindow::on_pushButton_clicked()
{
QString fileName = QFileDialog::getOpenFileName(this,tr("Open .off model"), "/home", tr("*.off"));
draw_poly(fileName);
}
void MainWindow::draw_poly(QString fileName)
{
QByteArray inBytes;
const char *c;
inBytes = fileName.toUtf8();
c = inBytes.constData();
std::ifstream input(c);
if (!input || !(input >> mesh) || mesh.is_empty()) {
std::cerr << "Not a valid off file." << std::endl;
// return 1;
}
input >> mesh;
CGAL::draw(mesh);
}
when I ran it , it open dialog file to select .off file ,then it shows the following error:
QCoreApplication::exec: The event loop is already running
any help ,please ?
I'm using Qt5 in daily business, and once considered CGAL as possible application base (without going further into this direction – not yet). Hence, this question made me curious.
I digged through the source code of CGAL on github and found out why the error message
QCoreApplication::exec: The event loop is already running
occurs.
For this, I copied the relevant lines from CGAL on github: Polyhedron/include/CGAL/draw_polyhedron.h:
template<class Polyhedron, class ColorFunctor>
void draw(const Polyhedron& apoly,
const char* title,
bool nofill,
const ColorFunctor& fcolor)
{
#if defined(CGAL_TEST_SUITE)
bool cgal_test_suite=true;
#else
bool cgal_test_suite=false;
#endif
if (!cgal_test_suite)
{
int argc=1;
const char* argv[2]={"polyhedron_viewer","\0"};
QApplication app(argc,const_cast<char**>(argv));
SimplePolyhedronViewerQt<Polyhedron, ColorFunctor>
mainwindow(app.activeWindow(), apoly, title, nofill, fcolor);
mainwindow.show();
app.exec();
}
}
Looking at this source code, it becomes obvious that CGAL::draw() is a small ful-featured Qt application in itself which establishs its own QApplication instance. The OP in turn tried to embed the CGAL::draw() in her/his own Qt application. It is not allowed to instance any derivates of QCoreApplication more than once (according to Qt doc. of QApplication):
For any GUI application using Qt, there is precisely one QApplication object, no matter whether the application has 0, 1, 2 or more windows at any given time.
(Emphasizing not mine.)
The CGAL doc. provides an (even shorter) example in Polyhedron/draw_polyhedron.cpp to do this right:
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Polyhedron_3.h>
#include <CGAL/IO/Polyhedron_iostream.h>
#include <CGAL/draw_polyhedron.h>
#include <fstream>
typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;
typedef CGAL::Polyhedron_3<Kernel> Polyhedron;
int main(int argc, char* argv[])
{
Polyhedron P;
std::ifstream in1((argc>1)?argv[1]:"data/cross.off");
in1 >> P;
CGAL::draw(P);
return EXIT_SUCCESS;
}
but there is no place to insert the QFileDialog at the right point.
Hence, CGAL::draw() is the wrong tool for what OP (probably) intends to do – embed CGAL polyhedron rendering into a Qt application. For this, it is necessary to use the things directly which are called somewhere inside of CGAL::draw().
So, this is what seems appropriate to me:
making SimplePolyhedronViewerQt<Polyhedron, ColorFunctor> a (main or child) widget in OPs Qt application.
I then walked a bit through the github repo to find out from which Qt widget CGAL::SimplePolyhedronViewerQt<Polyhedron, ColorFunctor> is actually derived from and found the following inheritance:
CGAL::SimplePolyhedronViewerQt<Polyhedron, ColorFunctor>
|
V
CGAL::Basic_viewer_qt
|
V
CGAL::QGLViewer
|
+--------------+--------------+
| |
V V
QOpenGLWidget QOpenGLFunctions
So, CGAL::SimplePolyhedronViewerQt<Polyhedron, ColorFunctor> can be used like any QWidget (which involves making it the main window). It can become as well the center widget of a QMainWindow which gets a menu bar/tool bar with the QAction to open the QFileDialog, request a file path, open a file stream with this file path, and load a mesh from this file stream.
There is another minor detail where I stumbled over: The CGAL::Polyhedron has to be given to the CGAL::SimplePolyhedronViewerQt in the constructor and by const reference. To consider this, it's IMHO necessary (after successful loading of mesh) to construct the CGAL::SimplePolyhedronViewerQt instance by new and set/add it to parent widget afterwards. If this is not acceptable it's probably necessary to go even deeper and replace the CGAL::SimplePolyhedronViewerQt by an own implementation, using the source code of the former as “cheat-sheet”.
This is how such an application could look like:
#include <fstream>
#include <QtWidgets>
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Polyhedron_3.h>
#include <CGAL/IO/Polyhedron_iostream.h>
#include <CGAL/draw_polyhedron.h>
typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;
typedef CGAL::Polyhedron_3<Kernel> Polyhedron;
int main(int argc, char **argv)
{
qDebug() << "Qt Version:" << QT_VERSION_STR;
QApplication app(argc, argv);
CGAL::DefaultColorFunctorPolyhedron fColor;
Polyhedron mesh;
// setup UI
QMainWindow qWin;
QToolBar qToolbar;
QAction qCmdLoad(QString::fromUtf8("Load File..."));
qToolbar.addAction(&qCmdLoad);
qWin.addToolBar(&qToolbar);
qWin.show();
// install signal handlers
QObject::connect(&qCmdLoad, &QAction::triggered,
[&qWin, &mesh, &fColor]() {
const QString filePath = QFileDialog::getOpenFileName(
&qWin,
QString::fromUtf8("Open .off model"),
QString::fromUtf8("/home"),
QString::fromUtf8("*.off"));
if (filePath.isEmpty()) return;
std::ifstream fIn(filePath.toUtf8().data());
if (!(fIn >> mesh) || mesh.is_empty()) {
qDebug() << "Loading of" << filePath << "failed!";
return;
}
qWin.setCentralWidget(
new CGAL::SimplePolyhedronViewerQt<Polyhedron, CGAL::DefaultColorFunctorPolyhedron>(
&qWin, mesh, "Basic Polyhedron Viewer", false, fColor));
qWin.centralWidget()->show();
});
// runtime loop
return app.exec();
}
Please, take this with a “grain of salt” – I've no CGAL at hand and couldn't compile/test the above code.
CGAL::draw() already handles the Qt stuff. You are trying to open a mainwindow in another one. Just call CGAL::draw(mesh) in your main() function without anything else and it will work.
EDIT: Which is exactly what Sheff explained in a much more detailed way.

qt memory issues with camerainfo and combobox.currentText()

I am trying to grab the names of webcams plugged into my computer and shove them into a combobox, then access the name later. Here is my code:
#include <QApplication>
#include <QComboBox>
#include <QCameraInfo>
#include <iostream>
int main(int argc, char *argv[])
{
QApplication app{ argc, argv };
QComboBox combo;
QList<QCameraInfo> info = QCameraInfo::availableCameras();
foreach(QCameraInfo i, info)
combo.addItem(i.description());
combo.show();
std::cout << combo.currentText().toStdString() << std::endl;
return app.exec();
}
The code creates and shows a combo box that has the name of a webcam that I have plugged in to the computer. It will then toss me an access violation exception in trying to print the combo box string to the console.
If I comment the cout line out, all is well, but on exit I get a Debug Assertion Failed! message:
Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)
which I take to mean I am deleting an object that has been deleted (the QString in the combobox???).
If I change the code to fill the combo box with dummies:
#include <QApplication>
#include <QComboBox>
#include <QCameraInfo>
#include <iostream>
int main(int argc, char *argv[])
{
QApplication app{ argc, argv };
for(int i=0; i<2; i++)
combo.addItem(QString("la la la");
combo.show();
std::cout << combo.currentText().toStdString() << std::endl;
return app.exec();
}
I get the same error on the cout, but if I comment that line out, the application exits correctly. I am using Visual Studio 2013, Windows 7, and Qt5.
Now it works. I kept the same source code, but completely scrapped the existing project and started a new one from scratch.
I've discovered that if I set the Runtime Library flag to Multi-Threaded DLL Debug, I will get access violation errors. If I set it to Multi-Threaded DLL, it is fine.
There may have been some other project settings that contributed, but this seems to be the main culprit.

QTextObjectInterface with Qml TextEdit (QQuickTextEdit)

I registred handler for simple QTextObjectInterface, that draws just 10x10 red rectangle.
When i used QTextEdit in normal QWidget app, it worked.
When i used QQuickTextEdit (TextEdit qml component) in Qt Quick app, it doesn't worked (nothing is drawed, but the rectangle in TextEdit is reserved, because when i change cursor position, i notice that there is something, but just empty space, nothing is drawed.
The QTextObjectInterface intrinsicSize method is called (that explains why i see there is empty space 10x10), but the drawObject method isn't.
I did some research and i found that actually the problem is probably here:
QQuickTextEdit.cpp from Qt 5.3.0 sources (line 1821)
QSGNode *QQuickTextEdit::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *updatePaintNodeData) {
.
.
.
if (textFrame->firstPosition() > textFrame->lastPosition()
&& textFrame->frameFormat().position() != QTextFrameFormat::InFlow) {
updateNodeTransform(node, d->document->documentLayout()->frameBoundingRect(textFrame).topLeft());
const int pos = textFrame->firstPosition() - 1;
ProtectedLayoutAccessor *a = static_cast<ProtectedLayoutAccessor *>(d->document->documentLayout());
QTextCharFormat format = a->formatAccessor(pos);
QTextBlock block = textFrame->firstCursorPosition().block();
node->m_engine->setCurrentLine(block.layout()->lineForTextPosition(pos - block.position()));
node->m_engine->addTextObject(QPointF(0, 0), format, QQuickTextNodeEngine::Unselected, d->document,
pos, textFrame->frameFormat().position());
nodeStart = pos;
}
it never reaches the point where node->m_engine->addTextObject is called.
It is because
this part of if condition textFrame->firstPosition() > textFrame->lastPosition() is evaluated to false.
I tried std::cout the firstPostion and the lastPosition when i established the context and firstPosition is 0, lastPosition is 1.
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QTextDocument>
#include <QQuickTextDocument>
#include <iostream>
#include <QTextCursor>
#include <QTextBlock>
#include <QPainter>
#include <QAbstractTextDocumentLayout>
#include <QTextCharFormat>
#include "qmlcomponentspace.h"
#include <QTextEdit>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
QTextDocument * doc = engine.rootObjects().first()->findChild<QObject *>("editor")->property("textDocument").value<QQuickTextDocument *>()->textDocument();
QTextCursor cur(doc);
int objectType = QTextFormat::UserObject + 1000;
QmlComponentSpace * component = new QmlComponentSpace();
doc->documentLayout()->registerHandler(objectType, component);
QTextCharFormat fmt;
fmt.setObjectType(objectType);
fmt.setForeground(Qt::red);
fmt.setBackground(Qt::red);
cur.movePosition(QTextCursor::End);
cur.insertText(QString(QChar::ObjectReplacementCharacter), fmt);
std::cout << "FIRST:" << doc->rootFrame()->firstPosition() << std::endl;
std::cout << "END:" << doc->rootFrame()->lastPosition() << std::endl;
return app.exec();
}
What i am missing?
The documentation says at
http://doc.qt.io/qt-5/qquicktextdocument.html#details
Warning: The QTextDocument provided is used internally by Qt Quick elements to provide text manipulation primitives. You are not allowed to perform any modification of the internal state of the QTextDocument. If you do, the element in question may stop functioning or crash.

Qt 5 QPrinterInfo::availablePrinters() not listing printers dynamically

I am updating the printer list using availablePrinters(). But it fails to list the new printer added while running application. It is working fine with Qt 4.
The code can be seen below:
#include <QCoreApplication>
#include <QtPrintSupport/QPrinterInfo>
#include <QThread>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
while (1) {
QThread::msleep(3000);
qDebug()<<"List of printers";
QList<QPrinterInfo> printerList=QPrinterInfo::availablePrinters();
foreach (QPrinterInfo printerInfo, printerList) {
qDebug()<<printerInfo.printerName();
}
}
return a.exec();
}
That was a bug with the existing Qt version, and It got fixed on the next version

ReferenceError when using c++ and qml on Nokia N9

I want to integrate c++ and qml. However, my code works fine in simulator but not in Nokia N9 (Qt 4.7.4 harmattan_10.2011.34-1)
Here is my code
I pasted c++ and qml code here for your reference
#include <QtGui/QApplication>
#include <QtDeclarative/QDeclarativeView>
#include <QtDeclarative/QDeclarativeContext>
#include <QtDeclarative/QDeclarativeEngine>
#include "qmlapplicationviewer.h"
#include "data.h"
#include "testfactory.h"
Q_DECL_EXPORT int main(int argc, char *argv[])
{
QScopedPointer<QApplication> app(createApplication(argc, argv));
TestFactory *testfactory = new TestFactory();
QScopedPointer<QmlApplicationViewer> viewer(QmlApplicationViewer::create());
QDeclarativeContext *context = viewer->rootContext();
context->setContextProperty("testfactory", testfactory);
viewer->setOrientation(QmlApplicationViewer::ScreenOrientationLockPortrait);
viewer->setMainQmlFile(QLatin1String("qml/main.qml"));
viewer->showExpanded();
testfactory->intilize();
return app->exec();
}
Button {
id: startButton
text: qsTr("Start")
onClicked: {
mainview.state = "START"
testfactory.startMeasurement()
}
}
The wield part is that the code works on simulator but the device.
The error I get is ReferenceError: Can't find variable: testfactory
Any one knows what the reason is?
Based on comments from irc qt-qml, one solution is to just use
QmlApplicationViewer *viewer = new QmlApplicationViewer();
instead of
QScopedPointer<QmlApplicationViewer> viewer(QmlApplicationViewer::create());
Then code works.