Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Qt's 'connect()' and virtual slot function
Forum Updated to NodeBB v4.3 + New Features

Qt's 'connect()' and virtual slot function

Scheduled Pinned Locked Moved Unsolved General and Desktop
2 Posts 2 Posters 1.9k Views 2 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • divergerD Offline
    divergerD Offline
    diverger
    wrote on last edited by diverger
    #1

    See the code below:

    
    class Base : public QObject
    {
    	Q_OBJECT
    
    public:
    	Base(QObject *p = nullptr)
    		: QObject(p)
    	{
    	}
    
    	void initb()
    	{
    		connect(this, &Base::sig, this, &Base::slot1, Qt::UniqueConnection);
    	}
    
    signals:
    	void sig();
    
    	public slots:
    	virtual void slot1()
    	{
    		// blabla....
    		qDebug() << "base";
    	}
    };
    
    
    class Derived : public Base
    {
    	Q_OBJECT
    
    public:
    	Derived(QObject *p = nullptr)
    		: Base(p)
    	{
    	}
    
    	void initd()
    	{
    		Base::initb();
    	}
    
    	void sig_emit()
    	{
    		emit sig();
    	}
    
    	public slots:
    	virtual void slot1()
    	{
    		// blabla
    		qDebug() << "derived";
    	}
    };
    
    
    int main(int argc, char *argv[])
    {
    
    	Derived derived;
    
    	derived.initd();
    	derived.sig_emit();
    }
    
    

    It will output "derived", that is, the base class's connect option, connect the signal to the derived class's slot. But apparently the arguments I passed to the connect function is the base class's 'this' pointer and the base class's 'slot1()' function pointer. It's a bit confused to me. Can someone explain it more?

    1 Reply Last reply
    0
    • A Offline
      A Offline
      ambershark
      wrote on last edited by
      #2

      Well you didn't really instantiate a Base object. So the this pointer is a Derived object. You are calling Base::initb() inside of your Derived object. So when it gets to the connect call inside initb the this pointer will be the one pointing at the derived object.

      Also since you derived your slot1() function as a virtual then Base::slot1 that is passed to the connect will point to the derived function.

      My L-GPL'd C++ Logger github.com/ambershark-mike/sharklog

      1 Reply Last reply
      5

      • Login

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • Users
      • Groups
      • Search
      • Get Qt Extensions
      • Unsolved