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

冷暖自知 提交于 2019-12-25 00:21:25

问题


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

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/16859507/how-to-call-a-static-function-as-a-slot-in-qt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!