mercredi 22 avril 2015

QT : Accessing secured resources only when login is complete via REST

I am working in a QT application in which I am accessing secured resources over REST. To access secured resources, I am initially logging-in and then saving the cookie in cookieManager. Once that is done, the manager is requesting via GET the secure object.

The problem I am currently facing is because the login is not complete, and I am requesting secure resource, I am getting Access Denied in the debug logs. Because of this I guess the request is getting repeated, and I am getting the ouput multiple times.

I want to only access secure resource when the login is successful while maintaining the contents of cookieManager and not make multiple requests. I tried to do that in SLOT when request is finished, but it goes in infinite loop.

Qt code :

void Person::loginAndAccess (){

    QString url_str = "http://localhost:8080/j_spring_security_check";
    QString canvasUrl = "http://localhost:8080/rest/jsonlist";

 QNetworkAccessManager *manager = new QNetworkAccessManager();
    manager->setCookieJar (new QNetworkCookieJar(manager));
    connect (manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(slotRequestFinished(QNetworkReply*)));
    QNetworkRequest request;
    request.setUrl (url_str);
    request.setRawHeader("User-Agent", "MyOwnBrowser 1.0");
    QByteArray postData;
    postData.append ("j_username=email@email.de");
    postData.append ("&j_password=password");
    manager->post (request,postData);
// From here I am accessing secured resource
    request.setUrl (canvasUrl);
    request.setRawHeader("User-Agent", "MyOwnBrowser 1.0");
    manager->get (request);
}

void Person::slotRequestFinished(QNetworkReply *reply)
{

    reply->deleteLater();

        if(reply->error() == QNetworkReply::NoError) {
            // Get the http status code
            int v = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
            if (v >= 200 && v < 300) // Success
            {
                 // Here we got the final reply
                qDebug() << "Request was successful";
                QString replyText = reply->readAll();
                qDebug() << replyText;
                return;
            }
            else if (v >= 300 && v < 400) // Redirection
            {
                // Get the redirection url
                QUrl newUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
                // Because the redirection url can be relative,
                // we have to use the previous one to resolve it
                newUrl = reply->url().resolved(newUrl);

                QNetworkAccessManager *manager = reply->manager();
                QNetworkRequest redirection(newUrl);
                QNetworkReply *newReply = manager->get(redirection);
                QString reply = newReply->readAll ();
                qDebug() << reply;

                return; // to keep the manager for the next request
            }
        }
        else
        {
            // Error
            qDebug() << reply->errorString();

        }

        reply->manager()->deleteLater();
}

Output in QT :

""
""
Request was successful
"
// REPLY from Server ommitted from output

"
Request was successful
""
Request was successful
"
// Again reply from server cut off

"
Request was successful
""
Request was successful
"

// So on and so-forth.

What am I doing wrong. I am not that much expert in QT, any help would be nice. Thanks a lot.

How i can extract PIXEL from DICOM file?

I want to write a script to extract the PixelDATA of a DICOM file using c or c ++, I don't want to use external libraries like dicomsdl... if anyone can help me to write algorithm for extract and show image .

Drawing html with transparent background

I'm currently trying to draw an HTML formatted text of a QTextEdit into a QPixmap with a transparent background, to use it as an overlay for another widget.

My first attempt was, to use the QTextDocument of the QTextEdit and use drawContents() to draw it to a QPixmap.

As a second attempt, I passed the HTML to a QStaticText and painted this to my QPixmap, using a QPainter.

Both approaches paint the final text as expected, however, the background of the QPixmap is always grey. Also setting the background-color of the QTextEdit, inside the StyleSheet, to transparent does no change.

Is there any way, that I can make the background transparent?

Spring MVC : Controller redirecting to JSP page instead of giving Object via REST

I am working on a Spring-MVC application in which I am trying to access secured services over a QT application. I am successfully able to login and gain access to secured resources, but when I call a controller method which is designed to give back an array of the Objects requested, it sends back the entire JSP page via REST. Why is this happening and how can I remedy this situation??

Controller code :

@PreAuthorize("hasRole('ROLE_USER')")
    @RequestMapping(value = "/canvas/jsonlist", method = RequestMethod.GET)
    public @ResponseBody Canvas[] listJsonCanvas() {
        System.out.println("From rest authentication the username is "+this.personService.returnLoggedInUsersEmail());
        List<Canvas> canvasList = this.canvasService.listCanvasPerson();
        return canvasList.toArray(new Canvas[canvasList.size()]);
    }

Output is JSP page, so I am not pasting it here.

Security-application-context.xml :

 <import resource="servlet-context.xml" />

    <!-- Global Security settings -->
    <security:global-method-security pre-post-annotations="enabled" />
    <security:http pattern="/resources/**" security="none"/>

    <security:http create-session="ifRequired" use-expressions="true" auto-config="false" disable-url-rewriting="true">
        <security:form-login login-page="/login" login-processing-url="/j_spring_security_check" default-target-url="/canvas/list" always-use-default-target="false" authentication-failure-url="/denied.jsp" />
        <security:remember-me key="_spring_security_remember_me" user-service-ref="userDetailsService" token-validity-seconds="1209600" data-source-ref="dataSource"/>
        <security:logout delete-cookies="JSESSIONID" invalidate-session="true" logout-url="/j_spring_security_logout"/>
<!--    <security:intercept-url pattern="/**" requires-channel="https"/> -->
    <security:port-mappings>
        <security:port-mapping http="80" https="443"/>
    </security:port-mappings>
    <security:logout logout-url="/logout" logout-success-url="/" success-handler-ref="myLogoutHandler"/>

     <security:session-management session-fixation-protection="migrateSession">
         <security:concurrency-control session-registry-ref="sessionRegistry" max-sessions="1" expired-url="/login"/>
     </security:session-management>

    </security:http>

    <bean id="sessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl" />

    <!-- Rest authentication, don't edit, delete, add-->
    <bean id="springSecurityFilterChain" class="org.springframework.security.web.FilterChainProxy">

    <security:filter-chain-map path-type="ant">
        <security:filter-chain filters="persistencefilter,authenticationfilter" pattern="/login"/>
        <security:filter-chain filters="persistencefilter,logoutfilter" pattern="/logout"/>
        <security:filter-chain pattern="/rest/**" filters="persistencefilter,restfilter" />
    </security:filter-chain-map>
    </bean>

    <bean id="persistencefilter" class="org.springframework.security.web.context.SecurityContextPersistenceFilter"/>

    <bean id="authenticationfilter" class="com.journaldev.spring.utility.AuthenticationFilter">
        <property name="authenticationManager" ref="authenticationManager"/>
        <property name="authenticationSuccessHandler" ref="myAuthSuccessHandler"/>
        <property name="passwordParameter" value="pass"/>
        <property name="usernameParameter" value="user"/>
        <property name="postOnly" value="false"/>
    </bean>

    <bean id="myAuthSuccessHandler" class="com.journaldev.spring.utility.AuthenticationSuccessHandler"/>

    <bean id="myLogoutHandler" class="com.journaldev.spring.utility.MyLogoutHandler"/>

    <bean id="logoutfilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">

        <constructor-arg index="0" value="/"/>
        <constructor-arg index="1">
            <list>
                <bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler">
                    <property name="invalidateHttpSession" value="true"/>
                    <property name="clearAuthentication" value="true"/>
                </bean>
                <bean id="myLogoutHandler" class="com.journaldev.spring.utility.MyLogoutHandler"/>
            </list>
        </constructor-arg>
    </bean>

    <bean id="httpRequestAccessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased">
        <property name="allowIfAllAbstainDecisions" value="false"/>
        <property name="decisionVoters">
            <list>
                <ref bean="roleVoter"/>
            </list>
        </property>
    </bean>

    <bean id="roleVoter" class="org.springframework.security.access.vote.RoleVoter"/>

    <bean id="restfilter" class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
        <property name="authenticationManager" ref="authenticationManager"/>
        <property name="accessDecisionManager" ref="httpRequestAccessDecisionManager"/>
        <property name="securityMetadataSource">
            <security:filter-invocation-definition-source>
                <security:intercept-url pattern="/rest/**" access="ROLE_USER"/>
            </security:filter-invocation-definition-source>
        </property>
    </bean>
    <!-- Rest authentication ends here-->

    <!-- queries to be run on data -->
    <beans:bean id="rememberMeAuthenticationProvider" class="org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices">
        <beans:property name="key" value="_spring_security_remember_me" />
        <beans:property name="tokenRepository" ref="jdbcTokenRepository"/>
        <beans:property name="userDetailsService" ref="LoginServiceImpl"/>
    </beans:bean>

    <!--Database management for remember-me -->
    <beans:bean id="jdbcTokenRepository"
                class="org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl">
        <beans:property name="createTableOnStartup" value="false"/>
        <beans:property name="dataSource" ref="dataSource" />
    </beans:bean>

    <!-- Remember me ends here -->
    <security:authentication-manager alias="authenticationManager">
        <security:authentication-provider user-service-ref="LoginServiceImpl">
           <security:password-encoder  ref="encoder"/>
        </security:authentication-provider>
    </security:authentication-manager>

    <beans:bean id="encoder"
                class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
        <beans:constructor-arg name="strength" value="11" />
    </beans:bean>

    <beans:bean id="daoAuthenticationProvider"
                class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
                <beans:property name="userDetailsService" ref="LoginServiceImpl"/>
               <beans:property name="passwordEncoder" ref="encoder"/>
    </beans:bean>
</beans>

Debug output :

DEBUG: org.springframework.web.servlet.DispatcherServlet - Rendering view [org.springframework.web.servlet.view.JstlView: name 'login'; URL [/WEB-INF/views/login.jsp]] in DispatcherServlet with name 'appServlet'
DEBUG: org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@99f857e1: Principal: org.springframework.security.core.userdetails.User@dde5c0af: Username: email@email.de; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_USER
DEBUG: org.springframework.web.servlet.view.JstlView - Added model object 'person' of type [com.journaldev.spring.model.Person] to request in view with name 'login'
DEBUG: org.springframework.web.servlet.view.JstlView - Added model object 'org.springframework.validation.BindingResult.person' of type [org.springframework.validation.BeanPropertyBindingResult] to request in view with name 'login'
DEBUG: org.springframework.security.access.vote.AffirmativeBased - Voter: org.springframework.security.access.prepost.PreInvocationAuthorizationAdviceVoter@5d046f29, returned: 1
DEBUG: org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - Authorization successful
DEBUG: org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - RunAsManager did not change Authentication object
DEBUG: org.springframework.web.servlet.view.JstlView - Forwarding to resource [/WEB-INF/views/login.jsp] in InternalResourceView 'login'
From rest authentication the username is email@email.de
DEBUG: org.springframework.web.servlet.DispatcherServlet - Rendering view [org.springframework.web.servlet.view.JstlView: name 'canvas'; URL [/WEB-INF/views/canvas.jsp]] in DispatcherServlet with name 'appServlet'
DEBUG: org.springframework.web.servlet.view.JstlView - Added model object 'canvases' of type [com.journaldev.spring.model.Canvas] to request in view with name 'canvas'
DEBUG: org.springframework.web.servlet.view.JstlView - Added model object 'org.springframework.validation.BindingResult.canvases' of type [org.springframework.validation.BeanPropertyBindingResult] to request in view with name 'canvas'
DEBUG: org.springframework.web.servlet.view.JstlView - Added model object 'mcanvas' of type [com.journaldev.spring.model.GroupCanvas] to request in view with name 'canvas'
DEBUG: org.springframework.web.servlet.view.JstlView - Added model object 'org.springframework.validation.BindingResult.mcanvas' of type [org.springframework.validation.BeanPropertyBindingResult] to request in view with name 'canvas'
DEBUG: org.springframework.web.servlet.view.JstlView - Added model object 'listGroups' of type [java.util.ArrayList] to request in view with name 'canvas'
DEBUG: org.springframework.web.servlet.view.JstlView - Added model object 'username' of type [java.lang.String] to request in view with name 'canvas'
DEBUG: org.springframework.web.servlet.view.JstlView - Added model object 'firstname' of type [java.lang.String] to request in view with name 'canvas'
DEBUG: org.springframework.web.servlet.view.JstlView - Forwarding to resource [/WEB-INF/views/canvas.jsp] in InternalResourceView 'canvas'
DEBUG: org.springframework.web.servlet.DispatcherServlet - Successfully completed request

Incase someone needs the QT code, here it is :

LoginAndAccessSecuresResource :

 QString url_str = "http://localhost:8080/j_spring_security_check";
    QString canvasUrl = "http://localhost:8080/canvas/jsonlist";

QNetworkAccessManager *manager = new QNetworkAccessManager();
    manager->setCookieJar (new QNetworkCookieJar(manager));
    connect (manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(slotRequestFinished(QNetworkReply*)));
    QNetworkRequest request;
    request.setUrl (url_str);
    request.setRawHeader("User-Agent", "MyOwnBrowser 1.0");
    QByteArray postData;
    postData.append ("j_username=email@email.de");
    postData.append ("&j_password=password");
    manager->post (request,postData);
    request.setUrl (canvasUrl);
    request.setRawHeader("User-Agent", "MyOwnBrowser 1.0");
    manager->get (request);

If there is any more information required, kindly let me know, more than happy to provide it. Thanks a lot. :-)

Get all elements of QListWidget

I have multiple instances of QListWidget on my UI. I would like to write all the elements of a specific QListWidget to a file.

How could I select every element of a specific QListWidget? (I already know how to write to a file...)

Internal QTimer isn't killed from the right thread when terminating a QThread

I have a QThread that creates a QGraphicsSimpleTextItem. When I close my application I try to finish the thread and then terminate it.

if( !QThread::wait(1000) )
    QThread::terminate();

Everything is fine until I add a call to QGraphicsSimpleTextItem::setFont() in my thread. If I do so, Qt's internal QFontCache system is called and will start a QTimer (from my thread). Then when I terminate the QThread, killTimer is called (from the main) when Qt cleans up the event loops and I get the error:

QObject::killTimers: timers cannot be stopped from another thread

What should I do to avoid this problem? Shouldn't that be considered as a bug of the font caching mechanism? Thanks for your help.

using boost whithin qt

I have installed qt-opensource-windows-x86-mingw491_opengl-5.4.1.exe and compile boost with mingw 4.9.1.
Now I want to link all boost libraries to my qt project likw what happened in visual studio.
any one can give a solution?

How to parse JSON for Qt Quick?

I am trying to do a simple programming to parse JSON message value from web to Qt Quick.

The JSON message would like to parse:

[
    {
         "id": 2,
         "name": "yahoo",
         "link": "http://www.yahoo.com/",
         "created_by": "superadmin",
         "create_time": "2015-03-12 14:45:21"
    },
    {
         "id": 3,
         "name": "Google",
         "link": "http://www.google.com/",
         "created_by": "superadmin",
         "create_time": "2015-03-12 14:45:41"
    },
    {
         "id": 4,
         "name": "PS",
         "link": "http://ift.tt/SdS6xU",
         "created_by": "superadmin",
         "create_time": "2015-03-24 11:57:21"
    }
]

The following is the Qt code main.cpp to try to parse these data:

#include <QGuiApplication>
#include <QStringList>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QNetworkAccessManager>
#include <QtScript/QScriptEngine>
#include <QtScript/QScriptValueIterator>
#include <qqmlengine.h>
#include <qqmlcontext.h>
#include <qqml.h>
#include <QtQuick/qquickitem.h>
#include <QtQuick/qquickview.h>

class Jsondata : QObject{
    QStringList datalist;
    public:
        void onResult (QNetworkReply*);
        QStringList datalistmethod() {
            return datalist;
        }
};

void Jsondata::onResult(QNetworkReply* reply)
{
    //if (m_currentReply->error() != QNetworkReply::NoError)
    //  return;  // ...only in a blog post

    QString data = (QString) reply->readAll();

    QScriptEngine engine;
    QScriptValue result = engine.evaluate(data);

    // Now parse this JSON according to your needs !
    QNetworkAccessManager networkManager;
    networkManager.setNetworkAccessible(QNetworkAccessManager::Accessible);

    QUrl url("http://***/api/web/v1/links");
    QNetworkRequest request;
    request.setUrl(url);

    QObject::connect(&networkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onResult(QNetworkReply*))); //Error. 
    networkManager.get(request);  // GET

    QString data = (QString) reply->readAll();

    QJsonDocument jsonResponse = QJsonDocument::fromJson(data.toUtf8());
    QJsonObject jsonObject = jsonResponse.object();
    QJsonArray jsonArray = jsonObject["name"].toArray();

    foreach (const QJsonValue & value, jsonObject) {
        QJsonObject obj = value.toObject();
        datalist.append(obj["name"].toString());
        datalist.append(obj["link"].toString());
    }
}

int main(int argc, char ** argv)
{
    QGuiApplication app(argc, argv);

    Jsondata jsondata;

    QStringList datalist;
    datalist = jsondata.datalistmethod();

    QQuickView view;
    QQmlContext *ctxt = view.rootContext();
    ctxt->setContextProperty("myModel", QVariant::fromValue(datalist));

    view.setSource(QUrl("qrc:main.qml"));
    view.show();

    return app.exec();
}

main.qml

import QtQuick 2.0
//![0]

ListView {
    width: 100; height: 100

    model: myModel
    delegate: Rectangle {
        height: 25
        width: 100
        Text { text: modelData }
    }
}
//![0]

Results in: onResult not called. so no datalist returned

I don't have knowledge on this QObject::connect and don't know what wrong. I would appreciate it if you could help me to fix this bug.

Updating progress bar during copying a large file size

How to update the progress bar to show the progress of copying a file because QFile documentation says:

"Unlike other QIODevice implementations, such as QTcpSocket, QFile does not emit the aboutToClose(), bytesWritten(), or readyRead() signals. This implementation detail means that QFile is not suitable for reading and writing certain types of files, such as device files on Unix platforms."

I would greatly appreciate any help on this. Thanks

mardi 21 avril 2015

How to set the width of the rectangle/area where text is drawn using QPainter::drawText() in QT?

I am quite new to 'QT' and api hooking . I have an application where i need to replace all it's original display text with specified target language text(in short-localization).After some research i came to know that QPainter::drawText() function is responsible to draw the text in the application.So i hooked it.Now i am able to change it's text to my language text.

But, issue is that when i forward my language text instead of it's original text,some characters of my text gets disappeared if my text width(i think i.e. number of characters)is greater than it's original text widht.

Here is screenshot for help:

![enter image description here][1]

red marked areas in the image.

So, please can anyone tell me how can i increase or decrease the width of the rectangle according to my text width.

please help me . . Thank you in advance.

StackView in ui.qml Forms

well, my question is very simple, i want to use the ui.qml files but i cant use Component and Loader insite these files, so for that reason i cant use StackView because for config the StackView i need use Component and loaders, so my question is, how i assign a Component and Loaders in main.qml of a StackView inside of WinForm.ui.qml? i alrady try this in MainForm.ui.qml file:

property alias stackV: stackV
...
StackView{
        id: stackV
    }
...

in main.qml file:

MainForm {
    anchors.fill: parent
    stackV{
        Component{
            id: comp1
            Loader {
                id:loader1
                source: "VentPrinc.qml"
            }
        }
    }
}

but i get this error

QQmlApplicationEngine failed to load component qrc:/main.qml:30 Cannot assign a value directly to a grouped property

i really appreciate any help

Load unity3d object in Qt QWebEngineView

Unity3D is loaded on Chrome using NPAPI plugin.

Like the same how do I load Unity3D in Qt QWebEngineView. Since NPAPI is being depreciated, which plugin can be made use of to load Unity3D.

Is it possible to directly load the Unity3D web player plugin in QWebEngineView

QTableWidget slot not calling function (argent)

.h

public slots:   
    void actCopy();
    void recordlocation(int,int);

_moc.cc

case 6: _t->actCopy();break;
case 7: _t->recordlocation((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
        default: ;
        }

.cc

connect(ui->actionCopy1,SIGNAL(clicked()), this, SLOT(actCopy()));
connect(ui->previewTable,SIGNAL(cellClicked(int, int)), this, SLOT(recordlocation(int, int)));

void
TimeSchedulerWindow::actCopy()
{   
    copy_cell(loc.row,loc.column);

}
void 
TimeSchedulerWindow::recordlocation(int row, int column)
{
    loc.row=row;
    loc.column=column;
    copy_cell(loc.row,loc.column);
}

other slot in my program is work....only this two slot not work.. i like calling slot() not calling the function anyone can help?

How to use Qt5 to realize MPICH2 function on windows? [on hold]

recently i am learning MPI on windows platform.i use MPICH2 to run the program(exe). MPICH2 graphical interface like this:

registering account in this interface

finding the hosts in the LAN interface

controling hosts to run program in this interface

I want to Recompile MPICH2 in Qt5 ,is it difficult? how to do it?

How to treat click events differently for an item's checkbox versus its text? (PyQt/PySide/Qt)

I have a QStandardItemModel in which each item is checkable. I want different slots to be called when I click on the item's checkbox, on one hand, versus when I click on its text, on the other. My ultimate goal is to have text edits, and changes in checkbox state, go onto the QUndoStack separately.

In my reimplementation of clicked I want to treat checkbox clicks and text clicks differently. So far, I have found no way to differentiate these events in the documentation for QCheckBox or QStandardItem. While QCheckBox has a toggled signal that I can use, I am not sure how to specifically listen for clicks on the text area.

I am trying to avoid having to set up coordinates manually and then listen for clicks in the different regions of the view of the item.

It doesn't seem this will be as simple as calling something like itemChanged, because that only gives you the new state of the item, not the previous state. Based on previous questions, I believe you need some way to pack the previous state into the undo stack, so you know what to revert to. That's what I am aiming to do with clicked, but there might be a better way.

This question piggybacks on the previous two in this series, in which I'm trying to figure out how to undo things in models:

Python 2.7 How to install PyQt4 on mac?

This isn't a question.

I had to figure out how to install PyQt4 on Mac and it was so difficult that I felt that I had to post the instructions here once I figured it out.

The video link contains the instructions that I used to install PyQt4 and the several other links are the links that are mentioned in the video.

Video Link : http://ift.tt/1DKVTLG

SIP Link : http://ift.tt/1uULDx9

PyQt Link : http://ift.tt/1lLQeM6

Qt 4.8.6 Link : http://ift.tt/1DOD65n

How to force widgets in QGridLayout be not equally spaced?

qGridLayout.addWidget(button1,    3,0,1,1, Qt::AlignBottom);
//qGridLayout.addWidget(button2,    3,1,1,1, Qt::AlignBottom);
// is there a way to make button1/3/4 stay at cell 1/3/4
// even if button2 is hidden
qGridLayout.addWidget(button3,    3,2,1,1, Qt::AlignBottom);
qGridLayout.addWidget(button4,    3,3,1,1, Qt::AlignBottom);

The problem I'm having is that, when I hide button2, button1/3/4 becomes automatically equally spaced.

I tried

qGridLayout.addItem(new QSpacerItem,3,1,1,1, Qt::AlignBottom);

but it doesn't work.

Persistent connection using QNetworkAccessManager in Qt

I'm trying to maintain a persistent connection between client and Remote server using Qt. My sever side is fine. I'm doing my client side in Qt. Here I will be using QNetworkAccessManager for requesting server with get method(Part of QNetworkRequest method). I will be able to send and receive requests.

But after sometime(approx ~ 2 min)the client is intimating server, the connection has closed by posting a request automatically. I think QNetworkAccessManager is setting a timeout for this connection. I want to maintain a persistent connection between the ends.

Is my approach correct, if not, can someone guide me in correct path?

Qt 5.4 return data from JavaScript function using document.getElementById

In QWebFrame.h there's a function evaluateJavaScript that returns a QVariant. In my app I've got a JavaScript function something like

return document.getElementById('theId').outerHTML when I call this function from the evaluateJavaScript Qt function I get back garbage as the QVariant (why I then turn into a QString). In my case if I use jQuery to get the HTML of the element I get the expected return value.

Even with simple cases it seems that document.getElementById does not work with Qt.

Is there a workaround besides adding another library like jQuery?

no match for call to '(QPalette)()' Qt4 in Linux

When I compiled an example code in QtCreator3.3.2 with Qt4.8.6 in Ubuntu14.04, this following error occurred:

videowidget.cpp:19: error: no match for call to '(QPalette) ()'
     palette = palette();
                       ^

in this snippet:

VideoWidget::VideoWidget(QWidget *parent) : QWidget(parent),surface(0)
{   
    setAutoFillBackground(false);
    setAttribute(Qt::WA_NoSystemBackground,true);
    setAttribute(Qt::WA_PaintOnScreen,true);

    palette = this->palette();//here's the error 
    palette.setColor(QPalette::Background,Qt::black);
    setPalette(palette);
    setSizePolicy(QSizePolicy::MinimumExpanding,QSizePolicy::MinimumExpanding);
    surface = new VideoWidgetSurface(this);
}

I looked up QPlalette class and QWidget class in Qt Assistant and manual of QWidget says:

Access functions:

const QPalette & palette () const

void setPalette ( const QPalette & )

which seems to me that QWidget has palette() function and so VideoWidget will definitely have it. But such error comes out. Thanks in advance.

errno 13 permission denied Pyththon QT

I followed a QT tutorial and now my end product doesn't work and exits with an errno 13 access denied. The program accepts a url to a file, as a string and a save location as a string. When the download button is pressed the error occurs. I am in a windows enviroment.

    import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import urllib.request


class Downloader(QDialog):
    def __init__(self):
        QDialog.__init__(self)

        layout = QVBoxLayout()

        self.url = QLineEdit()
        self.save_location = QLineEdit()
        progress = QProgressBar()
        download = QPushButton("Download")

        self.url.setPlaceholderText("URL")
        self.save_location.setPlaceholderText("File Save Location")

        progress.setValue(0)
        progress.setAlignment(Qt.AlignCenter)

        layout.addWidget(self.url)
        layout.addWidget(self.save_location)
        layout.addWidget(progress)
        layout.addWidget(download)

        self.setLayout(layout)

        self.setWindowTitle("Downloader")
        self.setFocus()

        # Connect Button press on Download to the download method.
        download.clicked.connect(self.download)

    def download(self):
        url = self.url.text()
        save_location = self.save_location.text()
        urllib.request.urlretrieve(url, save_location, self.report)

    def report(self, blocknum, blocksize, totalsize):
        read = blocknum * blocksize
        if totalsize > 0:
            percent = read * 100 / totalsize
            self.progress.setValue(int(percent))

app = QApplication(sys.argv)
dl = Downloader()
dl.show()
status = app.exec_()
sys.exit(status)

Qt QGraphicsItem middle mouse press event

I'm using Qt 5.3 on Linux. I have a QGraphicsScene and a QGraphicsItem. In my QGraphicsItem I implemented mousePressEvent, mouseReleaseEvent, mouseMoveEvent, to catch mouse events.

It works fine, but I have to double click to get a Middle button click event which is quite strange. Also I discovered that I don't get any mouse move event when nine of the buttons pressed.

I also implemented sceneEvent in my QGraphicsItem but that also misses the mouse mouve even unless a button is pressed, and only detect my middle button when I double click. I have a mouse with quite a few buttons but many button does not work at all in Qt, but works perfectly in other applications (xev gets the events properly).

Is there any way to to make the at least the middle mouse button work correctly?

How to run Qt Creator from console in Ubuntu?

I don't know how it's called in console.

Tried "qt", "qt-creator", "qtcreator". It not works.

Tried to find where Qt Creator is installed. I didn't find it.

Tried open qt from desktop. "./Qt\ Creator\ (Community)"

Command -ls showing the name as DigiaQt-qtcreator-community.desktop. "./DigiaQt-qtcreator-community.desktop". It doesn't work too.

I need it to run Qt Creator as root.

Handle FFMPEG dependency

I'm developping an application (using the Qt framework that has several dependencies like ffmpeg. Since I'm mostly developping for the MacOS plateform, I use Homebrew to manage my dependencies like ffmpeg.

As a result, I'm facing problem with unexpected API changes when the brew formula changes.

Homebrew mainteners advice me it's a bad practice to handle dependencies via brew. So I wonder what would be the best option?

I'm thinking about adding ffmpeg as a submodule of my project. What's your thought about it?

Qt main window destructor not called on exit?

I am coding a fairly simple application that uses Qt with OpenCV. I have single window that contains a widget which displays a video feed captured from a webcam. The webcam video capture is running in an infinite loop in a separate thread so as not to consume the UI thread.

When I close the window (using the normal "X" button on the top right of the window - this app is being developed in Windows 7), it doesn't seem to be shutting down the program correctly. The window does close visibly, but I put a breakpoint in the destructor of the main window, and the breakpoint never gets hit. Additionally, the thread which does video capture continues to run (I know this because the thread outputs to stdout periodically). Only when I click "stop debugging" in the Qt development environment does it cause everything to completely shut down.

Here is my worker object (not subclassing from QThread):

class Worker : public QObject
{
    Q_OBJECT
private:
    VideoCapture *cap;
    bool finished;
    QMutex mutex;
public:
    Worker ()
    {
        cap = new VideoCapture(0);
        finished = false;
    }

    bool isFinished ()
    {
        QMutexLocker locker (&mutex);
        return finished;
    }

public slots:
    void doWork ()
    {
        Mat frame;
        while(!isFinished())
        {
            // ...some code that outputs to stdout deleted for clarity...
            (*cap) >> frame;
            emit resultReady(frame);
        }
    }

    void setFinished (bool f)
    {
        QMutexLocker locker (&mutex);
        finished = f;
    }

signals:
    void resultReady (Mat frame);
};

Here is the header file for my main window:

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

    CVImageWidget* imageWidget;
    Worker *worker;
    QThread workerThread;

public slots:
    void handleResults (Mat frame);

signals:
    void operate ();
    void finishSignal (bool f);

private:
    Ui::MainWindow *ui;
};

And the class implementation:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //Create a widget for this window.
    QWidget *wdg = new QWidget(this);
    QGridLayout *grid = new QGridLayout(wdg);

    // ...code creating widgets deleted for clarity...

    this->setCentralWidget(wdg);

    //Start video capture
    qRegisterMetaType<Mat>("Mat");
    worker = new Worker();
    worker->moveToThread(&workerThread);
    connect(&workerThread, SIGNAL(finished()), worker, SLOT(deleteLater()));
    connect(this, SIGNAL(operate()), worker, SLOT(doWork()));
    connect(worker, SIGNAL(resultReady(Mat)), this, SLOT(handleResults(Mat)));
    connect(this, SIGNAL(finishSignal(bool)), worker, SLOT(setFinished(bool)));

    workerThread.start();
    emit operate();
}

MainWindow::~MainWindow()
{
    emit finishSignal(true);
    workerThread.quit();
    workerThread.wait();
    delete ui;
}

void MainWindow::handleResults(Mat frame)
{
    imageWidget->showImage(frame);
}

Any help understanding why the program doesn't shut down properly would be appreciated. Thanks!

How to generate objects on a window by a button click

I want a simple example code that shows QLineEdits by a QPushButton click on the same window. i.e. Whenever the button is clicked, a new line edit is displayed on the window. Or if i should put it this way; if the button is clicked 4 times, 4 line edits should be displayed on that same window Thank you!

PyQt4 - Dragging and dropping files into QPushButton

I think the title is fairly self explanatory. I'm working to create a small standalone app that requires the user to drag and drop audio files onto buttons to in turn associate the file with a corresponding button on a piece of hardware by using the filepath, etc...

I've followed a ton of drag and drop tutorials for widgets, and my friend has for lists, however I'm beginning to believe that it can't be done for a button? I'm aware that you can drag and drop text onto a button. I am not fully up to speed with Qt yet so there may just be a glaring error that I'm missing.

Here is the code, many thanks!

import sys
from PyQt4 import QtGui, QtCore

class Button(QtGui.QPushButton):
    def __init__(self, parent):
    super(Button, self).__init__(parent)
    self.setAcceptDrops(True)
    self.setDragDropMode(QAbstractItemView.InternalMove)

def dragEnterEvent(self, event):
    if event.mimeData().hasUrls():
        event.acceptProposedAction()
    else:
        super(Button, self).dragEnterEvent(event)

def dragMoveEvent(self, event):
    super(Button, self).dragMoveEvent(event)

def dropEvent(self, event):
    if event.mimeData().hasUrls():
        for url in event.mimeData().urls():
            path = self.addItem(url.path())
            print path
        event.acceptProposedAction()
    else:
        super(Button,self).dropEvent(event)

class MyWindow(QtGui.QWidget):
def __init__(self):
    super(MyWindow,self).__init__()
    self.setGeometry(100,100,300,400)
    self.setWindowTitle("Filenames")

    self.btn = QtGui.QPushButton()
    self.btn.setGeometry(QtCore.QRect(90, 90, 61, 51))
    self.btn.setText("Change Me!")
    layout = QtGui.QVBoxLayout(self)
    layout.addWidget(self.btn)

    self.setLayout(layout)

if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = MyWindow()
window.show()
sys.exit(app.exec_())

How do I create a QtWidgets ListView equivalent in Qt Quick Controls?

This question is a little specific, but I've been unable to find someone with the same problem or a clean solution to the problem.

I'm creating a Qt Quick program, and I want to use a QListView as it appears in QtWidgets. This QtWidgets program has three such views, with checkable items (which is optional: not all QListViews have checkable items).

Because Qt Quick Components doesn't appear to have a QListView equivalent, I set out to make my own from existing components. And the result is ... meh. It looks like this and doesn't exactly behave in the same fashion. Clicking on the text/whitespace of an item checks the item, instead of highlighting it. And the border is just ugly, and doesn't appear in GTK-themed environments. It also doesn't obey custom desktop themes, because the background of the items will always be white.

The code for this custom component is fairly brief, and looks like this:

import QtQuick 2.4
import QtQuick.Controls 1.3

// GroupBox creates a border... most of the time. Not in GTK envs
GroupBox {
    id: root
    property var model: null

    // This wraps the ListView up with a scrollbar
    ScrollView {
        anchors.fill: parent

        ListView {  // This is the view component
            anchors.fill: parent

            model: root.model

            // This is the white box that the CheckBox is drawn on
            delegate: Rectangle {
                width: parent.width
                height: box.height

                // This is the actual item
                CheckBox {
                    id: box
                    anchors.fill: parent
                    text: thing  // `thing` is just a placeholder value from the model
                }
            }
        }
    }
}

copying and moving QGraphicsItem from one QGraphicsScene to another, items snap to (0,0)

I am trying to create items in one panel and add to a second panel. In the second panel I want them to be movable (and have context menu). The AddItem button should add the item from the RenderArea, to the existing list of items in the CollectionView (which may already have been moved)

In the code below, the ShapeView::addItem() is supposed to create a copy of the item from the RenderArea (where it can change shape, color etc but is not movable, starts at (0,0)), place it in the CollectionView, where it is movable. The RenderArea holds one item - once added to CollectionView, the RenderArea item should reset.

What is happening... I can't seem to be able to separate the item from the two classes.

  • When I add item, even if the items in CollectionView have moved, their position resets to 0,0 (or whatever the initial position was in the RenderArea; but the adding works properly, the individual item properties are correct, like shape and color; also - CollectionView items move, RenderArea item doesn't).

I am posting all the relevant code:

class Item : public QGraphicsItem
{
    Item() { setFlag(ItemIsMovable, false); }   
    Item::Item(Item &copyItem) {         // copy constructor
        setFlag(ItemIsMovable); 
        setPos(copyItem.pos());    // doesn't seem to work
    QRectF boundingRect() const { return QRectF(-35, -30, 35, 20); }
    void Item::paint(QPainter *painter, const QStyleOptionGraphicsItem */*option*/, QWidget */*widget*/) { 
        painter->drawRect(boundingRect()); }

    QPointF p;  // temporary to fix position
protected:
    void mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
        QGraphicsItem::mouseMoveEvent(event);
    }
};

class CollectionView : public QGraphicsView
{
    Q_OBJECT    
public:
    CollectionView(QWidget *parent = 0);    
    void update();
    QList<Item*> *m_items;
};

CollectionView::CollectionView(QWidget *parent)
    : QGraphicsView(parent)
{
    QGraphicsScene *s = new QGraphicsScene(this);
    s->setSceneRect(-this->width()/2, -this->height()/2, this->width()/2, this->height()/2);
    setScene(s);
    setViewportUpdateMode(BoundingRectViewportUpdate);
    m_items = new QList<Item*>();
    scene()->clear();
}

void CollectionView::update()
{
    scene()->clear();
    for(int i = 0; i< m_items->size(); i++)
    {
        Item* item = new Item(*m_items->at(i));
        item->setPos(m_items->at(i)->p);  // doesn't seem to work
        scene()->addItem(item);
    }
    viewport()->update();
}

class RenderArea : public QGraphicsView
{
    Q_OBJECT
public:
    RenderArea(QWidget *parent = 0);    
public:
    Item* item;
};

RenderArea::RenderArea(QWidget *parent)
    : QGraphicsView(parent)
{
    QGraphicsScene *s = new QGraphicsScene(this);
    s->setSceneRect(-this->width()/2, -this->height()/2, this->width()/2, this->height()/2);
    setScene(s);
    setViewportUpdateMode(BoundingRectViewportUpdate);
    item = new Item();
    s->addItem(item);
}

// this is the boss/coordinator class
class ShapeView : public QGraphicsView
{
    Q_OBJECT
public:
    ShapeView(QWidget *parent = 0);
    CollectionView *collectionView;
private slots:    // more slots corresponding to more controls
    void addItem();
private:    
    QPushButton *addButton;
    RenderArea *renderArea;
};

ShapeView::ShapeView(QWidget *parent)
    : QGraphicsView(parent)
{
    collectionView = new CollectionView(parent);
    renderArea = new RenderArea(this);
    addButton = new QPushButton(tr("Add Item"));
    connect(addButton, SIGNAL(clicked()), this, SLOT(addItem()));
}

void ShapeView::addItem()
{   
    Item* item = new Item(*renderArea->item);
    collectionView->m_items->append(item);
    collectionView->update();

    // place a new item on renderarea
    renderArea->item = new Item();
    renderArea->scene()->clear();
    renderArea->scene()->addItem(renderArea->item);
    renderArea->viewport()->update();
}

Something is wrong in either the way I copy the item, I just don't know what. I see no reason why, when adding items, the CollectionView items all snap to the (0,0) position. Perhaps the issue is in the copy constructor but I can't figure what is wrong.

I hope someone can help give me a hint

Update: It seems that the problem is in the CollectionView::update() function... adding a 'delete' at the end of the loop removes the item from the collection... Or in the ShapeView::addItem() function... Am I creating copy of the item or just reusing it ?

But how do I create a copy of the item ?

Wrapping ListView inside rectangle

My problem is when i scroll ListView elements , the elements scroll over the rectangle border however i have wrapped the ListView inside the Rectangle.How can i make elements scroll without effecting the Rectangle borders.

Here are the result links http://ift.tt/1aPk1SX http://ift.tt/1bq8N8N

Following is the code

        ListModel{
        id: mod
    }
        Rectangle{
        id:listviewrec
        x: 347
        y:644
        width: 700
        height: 91
        radius: 4
        border.color:"#7CC7FF"
        border.width: 4
         visible: true

            ListView{
                id:modlistview
                width: listviewrec.width
                height: listviewrec.height
                clip: true
                boundsBehavior: Flickable.DragOverBounds
                spacing:25
                model:mod
                delegate: delegateimage
                orientation: Qt.Horizontal
                anchors.fill: listviewrec


            }

        }


    Component{
        id:delegateimage
        Item{
            id:imageitem
            width:50
            height:60
            visible:true
            Rectangle{
                id:imagerec
                x:10
                y:6
                width: 60
                height:70                    
                border.color: "#7CC7FF"
                border.width: 5
                radius: 2
                visible:true
                Image{
                    x: 3
                    y: 3
                    height : imagerec.height
                    visible: true
                    width : imagerec.width
                    anchors.fill: imagerec
                    source:fileUrl
                }
                                }
        }
    }

Read and view tab-delimited txt files in Qt C++ using QTableView

I need some general advice to point me in the correct direction of solving this problem: I have a .txt file with table data like the following:

Time    Pin
11:00   EIO4
12:55   EIO6
16:40   EIO4
20:10   EIO3

etc......

I need to be able to parse this .txt file. Then I need to display this table in Qt (perhaps in a QTableView).

I have looked into using QTableView, and it appears I pass a QAbstractItemModel* to the QTableView using QTableView::setModel(QAbstractItemModel* model), after which my QTableView will display whatever data is in the QAbstractItemModel (right?).

If that last paragraph was logical, then my next question is how do I construct a QAbstractItemModel using my .txt file? I don't see any functions in the documentation that do this? (Note: someone suggested creating a QStandardItemModel)

(Note, this paragraph is no longer relevant) QModelIndex createIndex(int row, int collumn, void* ptr) appears to have something to do with this, maybe? Maybe this creates a QModelIndex that can be passed to the QAbstractItemModel using QAbstractItemModel::insertRow(QModelIndex)? However I still don't know how to make these QModelIndex objects have anything to do with my .txt data.

QStandardItemModel documentation says

When you want a list or tree, you typically create an empty QStandardItemModel and use appendRow() to add items to the model, and item() to access an item. If your model represents a table, you typically pass the dimensions of the table to the QStandardItemModel constructor and use setItem() to position items into the table. You can also use setRowCount() and setColumnCount() to alter the dimensions of the model. To insert items, use insertRow() or insertColumn(), and to remove items, use removeRow() or removeColumn().

These functions that "add rows" take QList<QStandardItem*>'s as arguments, so I need to create QLists that each contain pointers QStandardItems that contain each cell's data?

So I will use

void QStandardItemModel::insertRow(int row, const QList<QStandardItem *> & items)

http://ift.tt/1aPk1CH

Along with an argument QList<QStandardItem*> generated by repeated calls of "<<" passing QStandardItem* pointers to an empty QList.

I will make QStandardItem's using the constructor

QStandardItem::QStandardItem(const QString & text)

where I get my QString text by parsing a QFile into QStrings.

Everything looking good?

Or maybe I should skip creating QLists and go directly from generating QStandardItem's to passing them into the QStandardItemModel using void QStandardItemModel::setItem(int row, int column, QStandardItem * item)

Edit: I ended up skipping creating QLists with the following process: QFile file -> QString line -> QStringList peices -> QStandardItem -> QStandardItemModel -> QTableView

Thanks to all who contributed

find max Char in QStringlist

How to remove all lines from QStringList which have QChar > 'R' ?

How to find max char in one line of QStringList ?

In the thread there is my first part of problem :

Issue with QThreadPool: fail to finish all the task?

I have the following code:

#include <QCoreApplication>
#include "myserver.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    MyServer server;
    server.startServer();

    return a.exec();
}
/////////////////////////////////////////////////
#include "myserver.h"
#include "myrunnable.h"

MyServer::MyServer(QObject *parent)
{
    pool = new QThreadPool(this);
    pool->setMaxThreadCount(10);
}

void MyServer::startServer()
{
    for (int i = 0; i < 11; i++)
    {
        MyRunnable *task = new MyRunnable();
        task->setAutoDelete(true);
        pool->start(task);
    }
}
/////////////////////////////////////////////////
#include "myrunnable.h"
#include <qdebug.h>
MyRunnable::MyRunnable()
{
}

void MyRunnable::run()
{
    qDebug() << "Run";
}

I run my code hoping by calling the startServer function it will give me 11 Run print on the screen. But it never did so. It printed out some Run on the screen but never all of them.

And the program even crash sometimes due to the stackoverflow. I checked the call stack and it is caused by some strange QMutex recursive.

So I assumed there must be some serious threading related issue with my code due the usage of QThreadPool and QRunnable. But I cannot figure out what it is even after reading the Qt's Docs...

Qt need help to disable scroll on combobox

Hello I need help to turn off scrool on combobox , I have written some code but I get error, can someone help me

list << ui->comboBox << ui->comboBox_2 << ui->comboBox_3;

for(i =0 ; i<list.count();i++)
{
    list[i]->installEventFilter(this);
    list[i]->setFocusPolicy(Qt::StrongFocus);



}

bool MainWindow::eventFilter(QObject * o,QEvent * e) {

if(e->type() == QEvent::Wheel && o == list.at(i) )
{
    return true;

}
return false;

} When i run program i get this Error ASSERT failure in QList::at: "index out of range"

QML: 'Steal' events from dynamic MouseArea

I'm currently trying to implement a drag-to-create mechanism in QML, but I've hit upon a problem where I need the newly created MouseArea to become the target of mouse events even though the original MouseArea hasn't had a mouse button release event yet.

Window {
    id: window
    width: 300
    height: 300

    Rectangle {
        id: base
        width: 20
        height: 20

        color: "red"

        MouseArea {
            anchors.fill: parent

            property var lastPoint
            property var draggedObj: null

            function vecLength( vec ) {
                return Math.abs( Math.sqrt( Math.pow( vec.x, 2 ) +
                                            Math.pow( vec.y, 2 ) ) );
            }

            onPressed: lastPoint = Qt.point( mouse.x, mouse.y )
            onPositionChanged: {
                if ( !draggedObj ) {
                    var diff = Qt.point( mouse.x - lastPoint.x,
                                         mouse.y - lastPoint.y );
                    if ( vecLength( diff ) > 4 ) {
                        draggedObj = dragObj.createObject( window );
                    }
                }

                mouse.accepted = !draggedObj;
            }
        }
    }

    Component {
        id: dragObj

        Rectangle {
            width: 20
            height: 20

            color: "blue"

            Drag.active: dragArea.drag.active
            Drag.hotSpot.x: 10
            Drag.hotSpot.y: 10

            MouseArea {
                id: dragArea
                anchors.fill: parent

                drag.target: parent
            }
        }
    }
}

If you run this code and try it, you will see that dragging in the red Rectangle causes the creation of the draggable blue Rectangle, but it won't follow the mouse because the red MouseArea is still receiving the mouse events despite the blue MouseArea being above it.

Is there any way of forcing the blue MouseArea to receive the mouse events?

QDir::remove() always causing a crash when called in specific SLOT

Everytime I call QDir::removeRecursively() my application crashes AFTER having removed the folder containing the files correctly. Having done some testing I found out that it depends on how I call the function. This is my code:

Recorder::Recorder(ParentClass *parent): QObject(parent){

     connect(this,SIGNAL(finishedRec(QString,QString)),this,SLOT(finishedRecording(QString,QString)));
}

void Recorder::start(){
    if (!recording){
        recording=true;
        recThread.reset(new std::thread(&Recorder::recordThread, this));
    }
}

void Recorder::stop(){
    recording = false;
    recThread->join(); recThread.reset();
}
void Recorder::recordThread(){
    QString picDir;
    QString filename;
    //....
    while(recording){
        //writing frames to folder
    }    
    emit finishedRec(picDir,filename);    
}

void Recorder::finishedRecording(QString picDir, QString filename){
    QProcess* proc = new QProcess();
    vecProcess.push_back(proc);
    vecString.push_back(picDir);
    proc->start("C:\\ffmpeg.exe", QStringList() <<"-i"<< picDir << "-r"<< "30" << "-vcodec"<< "ffv1" << filename);
    connect(proc,SIGNAL(finished(int)),this,SLOT(finishedProcess()));
}

void Recorder::finishedProcess(){
    for (int i=0; i<vecProcess.size();i++){
        if(vecProcess.at(i)->state()==QProcess::NotRunning){
            delete vecProcess.at(i);
            vecProcess.erase(vecProcess.begin() + i);

            QString folderToRemove=vecString.at(i);
            folderToRemove.chop(12);
            qDebug() << folderToRemove;
            QDir dir(folderToRemove);
            dir.removeRecursively();
            vecString.erase(vecString.begin() + i);

        }
    }
}

Only if I leave dir.removeRecursively() in, my application will always crash. Without it everything works as intended. Even deleting all the files with

QDir dir(path);
dir.setNameFilters(QStringList() << "*.*");
dir.setFilter(QDir::Files);
foreach(QString dirFile, dir.entryList()){
    dir.remove(dirFile);
}

will cause a crash AFTRER all the files were deleted.

I'm running my recordThead as a std::unique_ptr<std::thread>. I did try to run the thread as a QThread but that gave me the exact same result. If dir.removeRecursively() was called the program will crash after finishing the event in finishedProcess()

Calling removeRecursively() in a different event loop works. Why doesn't it work when using it in a SLOT like shown in my example?

Add an Icon to a QAction in toolbar

I'm working with Qt in visual studio. I want to add Icons in the menuBar of my application. Here is what I have so far :

QToolBar *View3DToolBar;
QAction * XYZviewAct;
XYZviewAct = new QAction(tr("3D view"), this);
XYZviewAct->setIcon(QIcon("3dicon.png"));
View3DToolBar->addAction(XYZviewAct);

The menu bar is shown but it doesn't display the Icon.

Has anyone done this using Qt/C++? Could anyone point me to a solution?

OpenGL dont clear to fill background color

I write the code to use OpenGL in Qt widget, this code like this:

GL_Widget::GL_Widget(QWidget *parent) :
    QGLWidget(parent)
{
}
void GL_Widget::initializeGL()
{
    glClearColor(0.2,0.2,0.2,1);
}

void GL_Widget::paintGL()
{
   glClear(GL_COLOR_BUFFER_BIT);
}

but the widget dont clear correct color as I code, it display background of desktop like the below image though I already set up widget inherit with my widget class, and set up the background of widget use style sheet. If I draw something like triangles, it clear correctly.But my purpose want clear it dont need to draw, so how can I do that?

Create vertical images list view [on hold]

How could create a vertical image list view like this without using 'qml' just by 'qt' and 'c++' So that each item could be select and handle click event.

When I get directoryChanged signal from QFileSystemWatecher the file newly added is not completed to read

I want to be notified when a file is added to "/test". So I used QFilesystemWatcher's directoryChanged signal. But when "cp aa.txt /test" I got directoryChanged signal and there when I read aa.txt I had incomplete aa.txt.

In this case how can I know the file is completed to read?

FYI, I can't use fileChanged signal since don't know exact file name.

Drag and drop from QTreeView to QListView with file copy in Qt5

I try to have a drag-and-drop from a Treeview (templates directory) to a Listview (project directory). I read that best solution is to implement mimeData() and dropMimeData() from Model. For now, I don't know what to put inside the functions and my test works only for drag.

I set them with as this :

Treeview :

  • model = QFileSystemModel (templates path)
  • dragEnable = true
  • dragDropMode = dragOnly
  • defaultDropAction = copyAction

Listview :

  • model = QFileSystemModel (project path) with ReadOnly=false
  • dragDropMode = dropOnly
  • sefaultDropAction = copyAction

Qt: make and install module on non-host platform

I am developing an app using a QML-based module (http://ift.tt/1D7uCk7) on OSX and would like to test the app on Android and iOS.

How do I set up the qmake file so that the module gets properly installed for the Android and iOS platforms (or, for that matter, any other non-host platform which I have in my Qt distribution) on my host system?

In this specific case, just copying the module folder to e.g. Qt/5.4/android_armv7/qml does not work as the module needs to install some QtQuick Styles and other stuff elsewhere as well.

QTDropbox: QDropbox - LNK1104: cannot open file Qt5Cored.dll

I am trying to build Qt-Dropbox in c++ (Visual studio on windows). I get the following error: cannot open file Qt5Cored.dll.

I added the following links to my project:

In VC++ Directories: VC++ Directories In Linker => Input: Linker => Input

How to rotate spectrogram Qwt

I'm new to GUI programming and I haven't had any luck finding an example of this. It seems like it should be very easy.

I am working with a QwtPlot, QwtPlotSpectrogram and a QwtMatrixRasterData, very similar to the Rasterview example. I have had success generating color maps, setting the display range, and getting the aspect ratio right for my raster data, but I haven't gotten anywhere with the coordinate systems on the canvas. I would like to draw the image rotated 90 degrees from what happens by default.

Is there an easy way to do this? Do you have to manually transpose the matrix values? Can you simply have it drawn roated?

Is it possible to use more than one uuid when using bluetooth device discovery in qt creator?

I'm programming a small qml app for android where I use the bluetoothdiscoverymodel in qt creator. I can already search for bluetoothdevices, see them in a listview and choose them to send some data(for examlple a picture). When I use a uuid, I can only find a device with that special uuid. That's clear so far. But is is possible to combine those two searches. At first I want to make a general search to find all devices around me. One of those devices I want to make to my default device and save this anywhere, my app connects automatically to, when it has been found. But in addition to this it should also search for other devices.

Below you see my code for the discovery, using a uuid.

Thanks for your help!

model:

BluetoothDiscoveryModel {
            id: btModel
            discoveryMode: BluetoothDiscoveryModel.MinimalServiceDiscovery
            uuidFilter: "e8e10f95-1a70-4b27-9ccf-d03972367ccc"

            onErrorChanged: {
                if (error == BluetoothDiscoveryModel.NoError)
                    return;
                if (error == BluetoothDiscoveryModel.PoweredOffError)
                {titleLabel.text = "Bluetooth turned off";
                    console.log("Please turn bluetooth on!")}
                else
                    titleLabel.text = "Cannot find devices";
            }

            onServiceDiscovered: {
                if(serviceFound)
                    return
                serviceFound = true
                console.log("Found new service " + service.deviceAddress + " " + service.deviceName + " " + service.serviceName);
                console.log("Connecting to Bluetooth server " + service.deviceName)
                socket.setService(service)
            }
        }
        BluetoothSocket {
            id: socket
            connected: true
            onSocketStateChanged: {
                console.log("Connected to Bluetooth server")
            }
            onStringDataChanged: {
                console.log("Received data: ")
                var data = remoteDeviceName + ": " + socket.stringData;
                data = data.substring(0, data.indexOf('\n'))
            }
        }

Qt Creator: add custom build configuration settings in .pro

I am trying to add build settings for a custom build configuration.

By default Qt Creator creates debug and release configurations (http://ift.tt/1DchTwK).

For those configs you can add custom build settings. For ex:

release: DESTDIR = $${build_root_dir}/release
debug:   DESTDIR = $${build_root_dir}/debug

I created another build configuration called debug_menu_active in Qt Creator. And I'd like to use the same kind of statements:

debug_menu_active: DEFINES += FORCE_ACTIVE_MENU_DEBUG
debug_menu_active: DESTDIR = $${build_root_dir}/debug_menu_active

Unfortunately it doesn't work message("DEFINES: "$${DEFINES}) gives:

Project MESSAGE: DEFINES :UNICODE QT_LARGEFILE_SUPPORT

I think I need to define something else, but I have no clue what it could be.

Could someone help me with this?

Thanks!

Using QWebEngine to render an image

I'm looking to replace QWebKit with QWebEngine in my headless renderer. I initialise the page with load() and connect a slot to loadFinished() to generate the final .PNG image. This used to work fine with WebKit but fails with QWebEngine.

Code is as follows...

_webView = new QWebEngineView();

....

// Render the HTML to an image
QPainter painter(&image);
_webView->page()->view()->render(&painter);
painter.end();

I receive the following errors :

"Asking for share context for widget that does not have a window handle" "QOpenGLWidget: Cannot be used without a context shared with the toplevel".

Does anyone have an example of rendering a screen using QWebEngine?

Thanks.

QQuickPaintedItem mouseReleaseEvent gets only called after doubleclick

I've derived a class from QQuickPaintedItem in which I want to handle the mousePressEvent and the mouseReleasEvent (and also the mouseMoveEvent but that is not my prolem now).

The mousePressEvent gets called properly everytime the left mouse button is pressed. But the mouseReleaseEvent gets only called after a double click. What I expected is to get the event everytime the button is released. How can I change this?

This is what I do:

MyView::MyView(QQuickItem *parent):
    QQuickPaintedItem(parent)
{
    setAcceptedMouseButtons(Qt::LeftButton);
}

void MyView::mousePressEvent(QMouseEvent *evt)
{
    //gets called after every single mouse click
    qDebug("mousePressEvent");
    if(evt->button() == Qt::LeftButton)
    {
        //do something...
        evt->accept();
    }
    else
    {
        evt->ignore();
    }
    QQuickPaintedItem::mousePressEvent(evt);
}

void MyView::mouseReleaseEvent(QMouseEvent *evt)
{
    //gets only called when releasing the mouse button after a double click
    qDebug("mouseReleaseEvent");
    if(evt->button() == Qt::LeftButton)
    {
        //do something...
        evt->accept();
    }
    else
    {
        evt->ignore();
    }
    QQuickPaintedItem::mouseReleaseEvent(evt);
}

Qt - Toggle A QAction To Set QStackedWidget's Current Widget

So what I am trying to do is when I press the showMenu (QAction), the container (QStackedWidget) changes the current widget to menuWidget AND when I press it again it hides.

Ok so I have managed to get this code:

connect(showMenu, SIGNAL(triggered()), map, SLOT(map()));
map->setMapping(menuWidget, container);
Object::connect(map, SIGNAL(mapped(QWidget *)), container, SLOT(setCurrentWidget(QWidget *)));

also if I run:

container->setCurrentWidget(menuWidget);

directly, it works fine, so I have not messed up in that way.

sending command to remote PC using LIBSSH

I using libssh to write command to remote PC.So its like (MY PC->Linux MAchine->Remote PC).iam able to to do port forwarding but when i try to exeute command let say ls -l its just wait .

For refrence here is my code :

void StartSession()
{
        int rc;
          m_host = "10.99.93.26";
          m_user = "embadmin";
          m_password = "#####";
          m_port = 22;
          m_loggedIn = false;
          m_session  = NULL;
          m_workingDirectory = ".";
          qRegisterMetaType<ConnectorWidget::SshError>("ConnectorWidget::SshError");
          int verbosity = SSH_LOG_FUNCTIONS;
          m_session = ssh_new();
          qDebug()<<"m_host.data()"<<m_host.toLatin1();
          // set the pertinant ssh session options
          ssh_options_set(m_session, SSH_OPTIONS_HOST, m_host.toLatin1());
          ssh_options_set(m_session, SSH_OPTIONS_USER, m_user.toLatin1());
          ssh_options_set(m_session, SSH_OPTIONS_LOG_VERBOSITY, &verbosity);
          ssh_options_set(m_session, SSH_OPTIONS_PORT, &m_port);

         int connectionResponse = ssh_connect(m_session);

         qDebug()<<"connectionResponse"<<connectionResponse;
         // if connection is Successful keep track of connection info.
         if (connectionResponse == SSH_OK)
         {
             qDebug()<<"Connectede";

         }
         else
         {
             qDebug()<<"Not Connected";

         }


         rc = ssh_userauth_password(m_session,NULL,m_password.toUtf8().constData());
         if ( rc == SSH_AUTH_SUCCESS)
         {
             qDebug()<<"Authenticated correctly";

         }

         ssh_channel channel;

         channel = ssh_channel_new(m_session);
         if (channel == NULL) qDebug()<<"channel NULL";
         rc = ssh_channel_open_session(channel);
         if (rc != SSH_OK)
         {
           ssh_channel_free(channel);
         }
    direct_forwarding(m_session);
    }

    void ConnectorWidget::direct_forwarding(ssh_session session)
    {

        char buffer[1024*1024];

         int total=0;
         int lastshown=4096;

        ssh_channel forwarding_channel;
         forwarding_channel = ssh_channel_new(session);;
        int rc = ssh_channel_open_forward(forwarding_channel,
                                      "10.99.92.80", 2222,
                                      "10.99.91.27", 80);

        if (rc != SSH_OK)
        {
            ssh_channel_free(forwarding_channel);
            qDebug()<<"rc after port forwarding";
        }
        rc = ssh_channel_request_exec(forwarding_channel, "cat > /dev/null");
         if (rc < 0) {
           ssh_channel_close(forwarding_channel);
           ssh_disconnect(session);

         }


         while ((rc = ssh_channel_write(forwarding_channel, buffer, sizeof(buffer))) > 0) {
           total += rc;
           if(total/2 >= lastshown){
             printf("written %llx\n", (long long unsigned int) total);
             lastshown=total;
           }
           if(total > LIMIT)
             break;
         }

         if (rc < 0) {
           printf("error : %s\n",ssh_get_error(session));
           ssh_channel_close(forwarding_channel);
           ssh_disconnect(session);

         }

         ssh_channel_send_eof(forwarding_channel);
         ssh_channel_close(forwarding_channel);

         ssh_disconnect(session);





    }

Can any body tell me whats wrong with this..

Thanks

Read attribute names and their values from a xml file in Qt using QDomNodeList

This is my xml file.

    <Dictionary EnglishName="English (United States)" CultureName="English (United States)" Culture="en-US">
         <Value Id="ID_OK" Translation="OK" English="OK" />
         <Value Id="ID_Cancel" Translation="Cancel" English="Cancel1" />
         <Value Id="ID_DemoMode" Translation="Demo Mode" English="Demo Mode" />
        <Value Id="ID_PhoneNumberColon" Translation="Phone Number:" English="Phone Number:" />
         <Value Id="ID_FaxNumberColon" Translation="Fax Number:" English="Fax Number:" />
         <Value Id="ID_CustomerColon" Translation="Customer:" English="Customer:" />
         <Value Id="ID_CompanyColon" Translation="Company:" English="Company:" />

I am able to get values of Id,Translation and English perfectly but i am not able to get the values of "EnglishName" ,"CultureName" and "Culture". This is my codesample,

QDomDocument doc("Labguage");
QFile file("English.xml");
if (!file.open(QIODevice::ReadOnly))
         return;

if (!doc.setContent(&file))
{
file.close();
         return;
}
file.close();

    QDomNode root = doc.namedItem("Dictionary");
    QDomNodeList nodeList = root.childNodes();
    if (nodeList.count() > 0)
    {
       for(int iDx = 0;iDx < nodeList.count(); iDx++)
        {
           QString EnglishName(nodeList.at(iDx).attributes().namedItem("EnglishName").nodeValue());
           QString CultureName(nodeList.at(iDx).attributes().namedItem("CultureName").nodeValue());
           QString Culture(nodeList.at(iDx).toElement().attribute("Culture"));

QString Translation(nodeList.at(iDx).attributes().namedItem("Translation").nodeValue()); QString English(nodeList.at(iDx).attributes().namedItem("English").nodeValue()); QString Id(nodeList.at(iDx).toElement().attribute("Id")); qDebug() << "Id: " << Id<

        }
     }
   I got EnglishName,CultureName and Culture as blank,where is my mistake, plz help me .

Thanks

Qt I want to encode a pointer as a string and decode it later

In my Qt app I'd like to encode a pointer to an object as a string, pass it to another bit of code then decode it so that I can access the object.

This is part of internal drag and drop with a QTreeView. In my mimeData() method I have:

QMimeData * TreeModel::mimeData(const QModelIndexList &indexes) const
{
    QMimeData *mimeData = new QMimeData();
    QByteArray encodedData;

    QDataStream stream(&encodedData, QIODevice::WriteOnly);

    foreach (QModelIndex index, indexes)
    {
        QString colText;
        if (index.isValid()) {
            TreeItem *item = getItem(index);

            // grab the text from each column 
            for(int cc=0; cc < item->columnCount(); cc++ ) {
                colText = item->data(cc).toString();
                stream << colText;
            }
            // add the pointer to the item 
            qDebug() << quint64(&item); 
            stream << quint64(&item);
        }
    }
    mimeData->setData("application/vnd.text.list", encodedData);

    return mimeData;
}

The qDebug() line produces a number like 140736277471632 which could be right, but is probably wrong.

How should I encode a pointer as a string so that it can be fed into a stream. And how should I then decode it and get the pointer to the original object?

Thank you.

How do QT focusproxies split focus between proxy and widget

Trying to create some custom widget as an aggregation of standard widgets, I came upon few things on focusproxies widget I cannot understand.

from QWidget doc :

void QWidget::setFocusProxy ( QWidget * w )
Sets the widget's focus proxy to widget w. If w is 0, the function resets this widget to have no focus proxy.
Some widgets can "have focus", but create a child widget, such as QLineEdit, to actually handle the focus. In this case, the widget can set the line edit to be its focus proxy.
setFocusProxy() sets the widget which will actually get focus when "this widget" gets it. If there is a focus proxy, setFocus() and hasFocus() operate on the focus proxy.

I am exactly in the situation above, a QLineEdit (plus some stuff without focus) in a custom QWidget.

Some point are still obscure to me : Once the proxy is set and working, no focus event are generated inside the original widget. In short, QWidget::focusOutEvent(QFocusEvent *event) is no longer called.

This sound strange to me, because it means that the widget getting the focus and forwarding it to any child widget lose all processing linked to this event. Doesn't look like a proxy to me but more like a delegate...

Could be I'm wrong and there is a deep meaning in doing that, in this case I'm 'deeply' interested too !

End of the day, I am also looking for an elegant solution to execute something upon a focus out event of a child widget (identical to focus out of my custom widget). I have the possibility to subclass systematically the child, reimplement the focusOutEvent handler and emit a signal inside the function that I will catch inside my custom widget. I find that this is however lacking elegance :(

thanks

QtUdpSocket - Sending too large datagram doesn't fail with "DatagramTooLargeError"

I came across a strange problem with QUdpSocket. Maybe this problem is known to you or any of you know how to handle it.

I'm developing with Qt 5.4.1 x86 on Windows 7 (x64), no firewalls are active.

Sending an UDP datagrams with "no fragment" bit set sometimes doesn't produce "DatagramTooLargeError" as expected but "SocketTimeoutError".

Setting "No Fragment" bit is done by native "setsockopt" method since Qt doesn't support this flag.

_Socket.bind(QHostAddress::AnyIPv4, 0, QAbstractSocket::ShareAddress);
unsigned int Flag = 1;
int ret = setsockopt(_Socket.socketDescriptor(), IPPROTO_IP, IP_DONTFRAGMENT, (const char*) &Flag, sizeof(Flag));

As I found out, "WSASendTo" in qnativesocketengine_win.cpp:1307 doesn't return SOCKET_ERROR in that case which shouldn't be the case. My first thought was, that setting "No Fragment" bit was lost some where, but how and where?

Following snippet of code causes this behaviour. Result return 16384 here which shouldn't be the case since "no Fragmentation" means, sending that large datagram is not possible.

qint64 Result = _Socket.writeDatagram((const char*) Message, 16384, _SenderAddress, _SenderPort);

Subsequent calls of the same "Send" command again give the expected result by returning an error. Calling the same command after one minute socket idle or so, no error is returned again, but then fail again the next call as expected.

This is a fully working Example Project to reproduce the described behaviour.

You should start this demo on two different computers. Enter the receiver IP address and port, and select an local sender adapter to bind to. Port can be left to zero. Then set "Don't fragment" and set the buffer size to 16384. After that you can press the "Send" button.

You will see something like this after pressing the send for the first time:

11:30:49,577: Sent 16384 bytes to 169.254.22.241:65430...

Pressing the button again and you will get the expected error message

Error sending datagram (Datagram was too large to send)

However after waiting a minute or so, you won't get that error again.

I was not able to reproduce this behaviour with pure windows socket implementation.

PS: I filled an Qt Bug report at QTBUG-45471. I refrain to repeat the complete text of the bug report here.

Qt. Sql. Connections in several threads

How can I create and use several connection to sql db in a different threads in the program using Qt?

I've read the documentation which says "A connection can only be used from within the thread that created it. "

How can I separate connections in a different threads?

QObject::connect failing with inheritance (no such slot, but Q_OBJECT macro defined)

My problem is best described by looking at some pseudo-code:

Headers:

class A: public QWidget
{
  Q_OBJECT

  public:
    void setupUserInterface(...);
    void funcA(...);
    void funcB(...);

  // etc..
}

class B: public A {
  Q_OBJECT

  // etc..
}

Implementation:

void A::setupUserinterface(...) // uiel1, uiel2 as input
{
  connect(uiel1, SIGNAL(pressed()), this, SLOT(funcA()));
  connect(uiel2, SIGNAL(pressed()), this, SLOT(funcB()));
}

void A::funcA(...) { ... }
void A::funcB(...) { ... }

When I try to build and run, I get the following errors:

QObject::connect: No such slot B::funcA in /.../A.cpp
QObject::connect: No such slot B::funcB in /.../A.cpp

Meaning that for some reason, it is looking for B-members in A.cpp.

How can I solve this? Thanks in advance.

Update 1: Making the functions funcA and funcB virtual does not help.

how to parse json with qt quick?

I am new to QT quick. I am trying to do a simple programming to parse JSON message value from web to QT quick. I have do the study and refer some codes from internet. However, I hit a but that make me can't go on.

The JSON message would like to parse:

    [
    {
      "id": 2,
      "name": "yahoo",
      "link": "http://www.yahoo.com/",
      "created_by": "superadmin",
      "create_time": "2015-03-12 14:45:21"
    },
    {
      "id": 3,
      "name": "Google",
      "link": "http://www.google.com/",
      "created_by": "superadmin",
      "create_time": "2015-03-12 14:45:41"
    },
    {
      "id": 4,
      "name": "PS",
      "link": "http://ift.tt/SdS6xU",
      "created_by": "superadmin",
      "create_time": "2015-03-24 11:57:21"
    }
    ]

The following is the QT code to try to parse these data: #include #include #include #include #include #include #include #include #include #include #include #include

            /*
               This example illustrates exposing a QStringList as a
               model in QML
            */




            class Jsondata {
                QStringList datalist;
            public:
                void onResult (QNetworkReply*);
                QStringList datalistmethod() {
                    return datalist;
                }
            };

            void Jsondata::onResult(QNetworkReply* reply)
            {
                //if (m_currentReply->error() != QNetworkReply::NoError)
                  //  return;  // ...only in a blog post

                QString data = (QString) reply->readAll();

                QScriptEngine engine;
                QScriptValue result = engine.evaluate(data);

                // Now parse this JSON according to your needs !
                QNetworkAccessManager networkManager;
                networkManager.setNetworkAccessible(QNetworkAccessManager::Accessible);

                QUrl url("http://***/api/web/v1/links");
                QNetworkRequest request;
                request.setUrl(url);

                QObject::connect(&networkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onResult(QNetworkReply*)));
                //Error. 
                networkManager.get(request);  // GET

                QScriptValue entries = result;
                QScriptValueIterator it(entries);
                while (it.hasNext()) {
                    it.next();
                    QScriptValue entry = it.value();

                    QString name = entry.property("name").toString();
                    QString link = entry.property("link").toString();

                    datalist.append(name);
                    datalist.append(link);
                }
            }

            int main(int argc, char ** argv)
            {
                QGuiApplication app(argc, argv);

                Jsondata jsondata;



                QStringList datalist;
                datalist = jsondata.datalistmethod();

                QQuickView view;
                QQmlContext *ctxt = view.rootContext();
                ctxt->setContextProperty("myModel", QVariant::fromValue(datalist));

                view.setSource(QUrl("qrc:main.qml"));
                view.show();

                return app.exec();
            }

There are error: candidate function not viable: no known conversion from 'Jsondata *' to 'const QObject *' for 3rd argument static QMetaObject::Connection connect(const QObject *sender, const char *signal

I don't have knowledge on this Qobject::connect and don't know what wrong. I would appreciate it if you could help me to fix this bug. Thank you.

Warm regards, Lapson

PyQt4 QAbstarctScrollArea fixed size in Qplaintextedit

Is there a way to set a fixed size of the scroll bar in a Qplaintextedit?

Initializing QGenericMatrix

I need a matrix for matrix multiplication for neural networks and since I use the Qt Framework which provides QGenericMatrix I thought I give it a try. But I have no idea how to initialize the matrix with data.

It got this constructor but I am not able to use it right.

QGenericMatrix::QGenericMatrix(const T * values)

So it would help if someone could give me an example initialization for e.g.

    QGenericMatrix<2,2,int> a();

If I search for QGenericMatrix I hardly find anything except the official class definition, so I was wondering if QGenericMatrix is a good choice at all?

How to get transformation matrix using old transformation matrics and co-ordinates?

Hello friends can any one clear me about what is w' in basic matrix operation formula in Qtransform below is code and what is difference between perspective and affine transform. Actually I am trying to find the at what values Img3 gets transformed?

x' = m11*x + m21*y + dx
y' = m22*y + m12*x + dy
if (is not affine) 
{
     w' = m13*x + m23*y + m33
     x' /= w'
     y' /= w'

}

lundi 20 avril 2015

graphicsview receives mouse event before the item

I have implemented the panning view on the QGraphicsView, using the mouse move event using

void View::mouseMoveEvent(QMouseEvent* event) {
pan();
QGraphicsView::mouseMoveEvent(event);
}

and in the scene of this view I have added few items where some of the items are resizable, so I implemented

void Item::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
 if(m_resizeMode)
    {
      resize();
      e->accept();
    }
}

I tried to filter the mouse move not to propagate to any further using e->accept() but my View mouseMove event has been called first , so when ever I tried to resize the item, the view started to pan all the way.

How can I avoid this event propagation from view to scene.

change language format of QDateTimeEdit

When language format of windows is changed (control panel -> region and language), the language format of Qt components (ex: QDateTimeEdit) will change consequently. How can I fix language format of these components (ex: to be always English).

Re-dock two QToolbars back in the same QToolbarArea

I'm working on a Qt project, where I need to get the toolbar positions at run-time. I used QMainWindow::toolBarArea(QToolBar *toolbar) to get the current docked area of the toolbar. And then I can use that later with QMainWindow::addToolBar ( Qt::ToolBarArea area, QToolBar * toolbar ).

Let's assume I dock two toolbars in a single area (i.e. Bottom area), as below.

-----------------------------------
| Toolbar 1                       |
-----------------------------------
| Toolbar 2                       |
-----------------------------------

Then I save the area obtained from QMainWindow::toolBarArea, using QSettings and then load them back with QMainWindow::addToolBar , it loads as below.

-----------------------------------
| Toolbar 1      | Toolbar 2      |
-----------------------------------

Is there any way to re-dock them the original form?

Best practice when accesessing derived classes in a QList

I have a base model where I have implemented the virtual members of QAbstractItemModel. I then use my base model in my project as needed by deriving new classes with specifics.

class BaseModel : public QAbstractItemModel{
    public:
        ...

    protected:
        QList<BaseItem*> list;
}

class DerivedModel : public BaseModel{
    public:
        ...
}

class DerivedItem : public BaseItem{
    public:
        ...
}

My derived model uses DerivedItem objects to store data which have some specifics that BaseItem doesn't have. They are stored in list. Methods in BaseModel uses objects in list as well.

My issues is because of this I have to type cast every time I access objects from list in the derived model. And I can't use macros like foreach.

Is there any tips or tricks I can use in this circumstance that will enable me to use macros and prevent me from type casting every time I access items from the list. Or is there another method (better practice) when making a common class to later derive from.

Thanks,

Autodesk Maya model panel resize event (PySide, PyQt)

I'm writing a simple tool menu for Maya, and I'd like to stick it to the border of model panel (perspective).

from PySide import QtCore, QtGui
from maya import OpenMayaUI as omui
from shiboken import wrapInstance

class TestWidget(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent = self.getMayaWindow())

        self.setWindowFlags(QtCore.Qt.Tool | QtCore.Qt.FramelessWindowHint)
        self.setFixedSize(100, 100)

        panelPtr = omui.MQtUtil.findControl('modelPanel4')
        panel = wrapInstance(long(panelPtr), QtGui.QWidget) 
        
        position =  panel.mapToGlobal(panel.pos())
        self.move(position.x(), position.y() + panel.geometry().height() / 2 - self.geometry().height() / 2)

        mainLayout = QtGui.QVBoxLayout(self)
        
        button = QtGui.QPushButton('CLOSE')
        button.setFixedSize(80, 80)
        button.clicked.connect(self.deleteLater)
        
        mainLayout.addWidget(button)

    def getMayaWindow(self):
        omui.MQtUtil.mainWindow()    
        ptr = omui.MQtUtil.mainWindow()
        return wrapInstance(long(ptr), QtGui.QWidget)

w = TestWidget()
w.show()

The main widget is positioned exactly where I want when it is created (horisontally on the left side of model panel, vertically - in the middle of model panel).

I need to reposition it accordingly when the model panel is resized, but model panel does not emit "resized()" signal. I'd appreciate any advise.

Qt C++ - Getting Audio Tempo with QMediaPlayer

I'm using QMediaPlayer to play audio in Qt with C++. I did find a class (QAudioProbe) to retrieve audio information. After spending a long time wondering why it was not working, I find out that QAudioProbe is incompatible with QMediaPlayer on my platform (OS X).

So is there a way I can retrieve audio information (specifically the song's tempo) from QMediaPlayer in Qt?

Qt. XML(QDomDocument) log class is not working

I'm trying to build an XML log using QDomDocument. But, unfortunately it isn't working. I'm new with XML so I can't spot the problem. Here is my Log class.

#ifndef LOG_H
#define LOG_H

#include <QtXml/QtXml>
#include <QDate>
#include <QtXml/QDomDocument>

class Log
{
private:
    static Log* instance;
public:
    static Log* getInstance();
    ~Log();
    bool appendRecord(QString& _emp_id, QString& _emp_name, QString& _action, QDate _date);
private:
    Log();
    QDomElement makeRecord(QDomDocument& _doc, QString& _emp_id, QString& _emp_name, QString& _action, QDate _date);
    QDomElement makeElement(QDomDocument& _doc, QString& _name, QString& _attribute, QString& _text = QString());
};

#endif // LOG_H

And here is .cpp-file.

#include "log.h"
#include <QFile>

Log* Log::instance = nullptr;

Log::Log()
{
    qDebug() << Q_FUNC_INFO;
}

Log::~Log()
{
    qDebug() << Q_FUNC_INFO;
    if(instance)
        delete instance;
}

Log* Log::getInstance()
{
    qDebug() << Q_FUNC_INFO;
    if(!instance)
        instance = new Log();
    return instance;
}

bool Log::appendRecord(QString& _emp_id, QString& _emp_name, QString& _action, QDate _date)
{
    qDebug() << Q_FUNC_INFO;
    QDomDocument doc("log");
    QDomElement elem = doc.createElement("log");
    QDomElement record = makeRecord(doc, _emp_id, _emp_name, _action, _date);

    elem.appendChild(record);
    QFile file(QString("log_%1_%2_%3.xml").arg(_date.year()).arg(_date.month()).arg(_date.day()));
    if(file.open(QIODevice::WriteOnly))
    {
        QTextStream(&file) << doc.toString();
        QTextStream(&file) << "END.";
        file.close();
        return true;
    }
    return false;
}

QDomElement Log::makeRecord(QDomDocument& _doc, QString& _emp_id, QString& _emp_name, QString& _action, QDate _date)
{
    qDebug() << Q_FUNC_INFO;
    static int number = 1;

    QDomElement elem = makeElement(_doc, QString("record"), QString::number(number));
    elem.appendChild(makeElement(_doc, QString("ID"), QString(), _emp_id));
    elem.appendChild(makeElement(_doc, QString("name"), QString(), _emp_name));
    elem.appendChild(makeElement(_doc, QString("action"), QString(), _action));
    elem.appendChild(makeElement(_doc, QString("date"), QString(), _date.toString()));


    number++;
    return elem;
}

QDomElement Log::makeElement(QDomDocument& _doc, QString& _name, QString& _attribute, QString& _text)
{
    qDebug() << Q_FUNC_INFO;
    QDomElement elem = _doc.createElement(_name);

    if(!_attribute.isEmpty())
    {
        QDomAttr attr = _doc.createAttribute("number");
        attr.setValue(_attribute);
        elem.setAttributeNode(attr);
    }

    if(!_text.isEmpty())
    {
        QDomText txt = _doc.createTextNode(_text);
        qDebug() << _text;
        elem.appendChild(txt);
    }
    return elem;
}

Sorry, It's a bit messy, long and case-specific, but I think you'll get the idea. Thank you.

I got errors: "QQmlApplicationEngine failed to load component" and "qrc:/main.qml:-1 File not found"

I created a Qt Widgets application, then added a qml named "main.qml" to it. My files are dialog.cpp, dialog.h, dialog.ui, main.cpp, untitiled9.pro, main.qml in qml.qrc

main.cpp:
#include "dialog.h"
#include <QApplication>
#include <QQmlApplicationEngine>
#include<QtQml>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Dialog w;
// w.show();
   QQmlApplicationEngine engine;
// engine.load(QUrl(QStringLiteral("qrc://main.qml")));
  engine.load(QUrl::fromLocalFile("qrc:///main.qml"));
return a.exec();

}

I wrote "QT += qml quick widgets" in untitled9.pro.
I didn't modified other codes, how did this happen? This is my first question in stackoverflow, I try to make my question clear.

How to run Qt Creator from console?

I don't know how it's called in console.

Tried "qt", "qt-creator", "qtcreator". It not works.

Tried to find where Qt Creator is installed. I didn't find it.

Tried open qt from desktop. "./Qt\ Creator\ (Community)"

Command -ls showing the name as DigiaQt-qtcreator-community.desktop. "./DigiaQt-qtcreator-community.desktop". It doesn't work too.

I need it to run Qt Creator as root.

C++ Qt5 - Program finishes before QThread

Let's take a look at the following code:

class CommandRetriever
{
    public:
        CommandRetriever();
        ~CommandRetriever();

        void addCommand( QString, Command* );
        void executeCommands();

    private:
        QMap<QString, Command*> m_commands;
};

addCommand should be self-explanatory; it will add a new entry into m_commands. However, let's take a look at the implementation of executeCommands...

void CommandRetriever::executeCommands()
{
    for( auto iter : m_commands.keys() )
    {
        Command *cmd = m_commands.value( iter ); 

        // Command, password //
        RemoteConnection *rcon = new RemoteConnection( cmd, "" );

        QThread *thread = new QThread();
        rcon->moveToThread( thread );
        QObject::connect( thread, SIGNAL( started() ), rcon, SLOT( doAsync() ) );
        QObject::connect( rcon, SIGNAL( finished() ), thread, SLOT( quit() ) );
        QObject::connect( rcon, SIGNAL( finished() ), rcon, SLOT( deleteLater() ) );
        QObject::connect( thread, SIGNAL( finished() ), thread, SLOT( deleteLater() ) );
        thread->start();
    }
}

My rcon object is a QObject which has the public slot doAsync() to do work off the main thread. All of this is per Qt official examples and what I was able to muster from various blogs.

This is a completely console-based program, so I have no Windows, Widgets, or event loops to work with.


The Problem

What happens is that my program will exit before any asynchronous work is able to be done (e.g. connect to a remote host, write data, etc). Sometimes, if I'm lucky, my threads will do work fast enough to output something, so I know that the threads are working as they should. My question is: How do I keep my main program running until my threads finish the work? Is there an official way of doing this in QThread? Because I haven't seen anything in the docs.

Thanks!


Addendum April 20, 2015

Although the accepted answer made by Jeremy in this question is correct, it makes less sense for console-based applications, where an event loop is typically not needed.

Thus, I asked a new question, and found an answer for those in search of using threads without Qt event loop non-sense:

QThread never quits due to QCoreApplication event loop