I have subclassed QTabWidget and added a new public slot. When I try to connect to that slot, Qt tells me that my slot doesn't exist. But seems to be looking in the parent class. What am I missing?
Here is a minimal program that reproduces the problem. I am running it in Qt 5.13 with a MinGW 32-bit package.
#include <QMainWindow>
#include <QApplication>
#include <QTabWidget>
#include <QTabBar>
#include <QDebug>
class MyTabWidget : public QTabWidget
{
public:
MyTabWidget(QWidget *parent) : QTabWidget(parent)
{
qDebug() << "connect() returns " <<
connect(this->tabBar(),SIGNAL(tabBarDoubleClicked(int)),this,SLOT(changeTabName(int)));
}
public slots:
void changeTabName(int index)
{
tabBar()->setTabText(index,"New Name");
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QMainWindow *mw = new QMainWindow();
QWidget *tw;
MyTabWidget *t = new MyTabWidget(mw);
tw = new QWidget(mw);
t->addTab(tw,"Double-click This Tab");
mw->setCentralWidget(t);
mw->show();
return a.exec();
}
Here is the output. When connect() is called, "this" is a pointer to the subclass, right? So why is it looking for the slot in the superclass?
QObject::connect: No such slot QTabWidget::changeTabName(int) in main.cpp:14
QObject::connect: (sender name: 'qt_tabwidget_tabbar')
connect() returns false
You have the following errors:
If a class that inherits from QObject like all widgets is going to have signals, slots, etc. then you must use the Q_OBJECT macro to create the necessary implementations associated with those elements. Therefore, if you are using Q_OBJECT in the main file (filename.cpp) then you must include "filename.moc" to include the above.
You must use the new connection syntax, although it is not an error but can be a source of silent bugs.
Considering the above, the solution is:
main.cpp
#include <QMainWindow>
#include <QApplication>
#include <QTabWidget>
#include <QTabBar>
#include <QDebug>
class MyTabWidget : public QTabWidget
{
Q_OBJECT
public:
MyTabWidget(QWidget *parent) : QTabWidget(parent)
{
qDebug() << "connect() returns " <<
connect(tabBar(), &QTabBar::tabBarDoubleClicked, this, &MyTabWidget::changeTabName);
}
public slots:
void changeTabName(int index)
{
tabBar()->setTabText(index,"New Name");
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QMainWindow *mw = new QMainWindow();
QWidget *tw;
MyTabWidget *t = new MyTabWidget(mw);
tw = new QWidget(mw);
t->addTab(tw,"Double-click This Tab");
mw->setCentralWidget(t);
mw->show();
return a.exec();
}
#include "main.moc"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.