How to call a static function as a SLOT() in Qt? [

2019-08-30 18:09发布

This question already has an answer here:

I am using Qt code in a ROS node. I have declared a static function setLabel() in my class. The role of this function is to put an image into a QLabel. Now, I want to call this function when I click a button using a signal/slot connection. Please tell me what should I put at place of the question mark.

class ImageDisplay: public QObject
{

Q_OBJECT    

    public slots:
    void setLabel();    

    public: 
    static void imageCallback( ); 

};


void ImageDisplay::setLabel()
{

        QLabel* selectLabel= new QLabel();
        selectLabel->setText("hi");     
        selectLabel->show();
}    

void imageDisplay::imageCallBack()
{
    ImageDisplay obj;

    QObject::connect(selectButton, SIGNAL(clicked()),&obj, SLOT(setLabel()));       
}

标签: qt qt-creator
2条回答
我命由我不由天
2楼-- · 2019-08-30 18:30

First, get rid of global variable. Why do you need it? Global variables are vary bad and should be avoided.
Second, add Q_OBJECT macro to myQtClass and do qmake.
Third, your setLabel() slot shouldn't be private, make it public if you want to use it outside of myQtClass.

查看更多
男人必须洒脱
3楼-- · 2019-08-30 18:42

You try this,

QObject::connect(selectButton, SIGNAL(clicked()), listenerObj, SLOT(setLabel()));

listenerObj is the object pointer of class that you declared your slot. If you are unable to use "this" in listener, you declare an active object which contains a public slot of your function setLabel and connect the slot.

declare setLabel() as public slot in header file of your new class

class SomeClass
{
public slots:
void setLabel();
}

then using parent pointer you could show the label in interface

I think some of this will help you.

查看更多
登录 后发表回答