Ошибка no matching function for call to qt

I am learning QT and am trying to get my signals and slots working. I am having no luck.
Here is my Main

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

      FilmInput fi;
      FilmWriter fw;
      QObject::connect (&fi->okButton, SIGNAL( clicked() ), &fi, SLOT( okButtonClicked() ) 

    ); //Error received Base operand of '->' has non-pointer type 'FilmInput'
     QObject::connect(&fi,SIGNAL(obtainFilmData(QVariant*)),&fw,SLOT(saveFilmData(QVariant*)));
//Error received No matching function for call to 'QObject::connect(Filminput*, const     char*, FilmWriter*, const char*)
      fi.show();
      return app.exec();

    }

and here is my sad attempt at signals and slots:

FilmInput.h

public:
        FilmInput();
        void okButtonClicked();
    QPushButton* okButton;
signals:
        void obtainFilmData(Film *film);
Here is FilmWriter.h

public slots:
    int saveFilm(Film &f);

Here is Film Input.cpp


void FilmInput::okButtonClicked(){
    Film *aFilm=new Film();
    aFilm->setDirector(this->edtDirector->text());
    emit obtainFilmData(aFilm);

}

Here is FilmWriter.cpp

void FilmInput::okButtonClicked(){
    Film *aFilm=new Film();
    aFilm->setDirector(this->edtDirector->text());
    emit obtainFilmData(aFilm);

}

Please assist me in getting the signals and slots to work, I have spent hours but am no closer to getting it working. I have added the errors received in my comments above.

Regards

rediculus

0 / 0 / 0

Регистрация: 23.04.2017

Сообщений: 9

1

18.05.2018, 10:51. Показов 9388. Ответов 10

Метки c, connect, qt (Все метки)


Студворк — интернет-сервис помощи студентам

Нужно, чтобы при нажатии на кнопку срабатывал метод класса Acceleration. Однако при компиляции происходит ошибка: no matching function for call to ‘MainWindow::connect(QPushButton*&, const char*, Acceleration&, const char*)’
QObject::connect(pushButton, SIGNAL(clicked()), first, SLOT(Acceleration::Set(float, QString)));

Connect писал как в main.cpp, так и в mainwindow.cpp, везде одно и то же. Сейчас он в mainwindow.cpp.

Долго искал в чем проблема, рылся по форумам, решение не нашел.
Код:

Acceleration.h:

Кликните здесь для просмотра всего текста

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#ifndef ACCELERATION_H
#define ACCELERATION_H
#include <QString>
#include "mainwindow.h"
#include <QObject>
 
class Acceleration : public QObject
{
//Q_OBJECT
private:
    QString dem;
    float acc = 0;
public:
    Acceleration();
 
 
public slots:
    void SetDem(QLineEdit s);
    void SetDem(int a);
    void Set(QString s);
    void Set(float a, QString s);
    void Set(float ac, int a);
 
};
 
#endif // ACCELERATION_H

mainwindow.h:

Кликните здесь для просмотра всего текста

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
 
#include <QMainWindow>
#include <QGridLayout>
#include <QPushButton>
#include <QLabel>
#include <QSize>
#include <QLineEdit>
#include <QComboBox>
#include <QString>
#include <QTextBrowser>
#include <QObject>
#include "acceleration.h"
 
namespace Ui {
class MainWindow;
}
 
class MainWindow : public QMainWindow
{
    Q_OBJECT
protected:
 
public:
    QString mS = "м/с^2";
    QString smS = "см/с^2";
    QLabel *setDem = new QLabel("Задать единицы измерения");
    QLabel *setAc = new QLabel("Задать величину");
 
    explicit MainWindow(QWidget *parent = 0);
    QHBoxLayout *mainLayout = new QHBoxLayout;
    //First acceleration
    QWidget *w1 = new QWidget;
    QGridLayout *layoutFirstAc = new QGridLayout;
    QLabel *firstAc = new QLabel("Ускорение 1");
    QLineEdit *setDemLine1 = new QLineEdit();
    QLineEdit *setAcLine1 = new QLineEdit();
 
    QPushButton *pushButton = new QPushButton("1");
    //Second acceleration
    QWidget *w2 = new QWidget;
    QGridLayout *layoutSecondAc = new QGridLayout;
    QLabel *secondAc = new QLabel("Ускорение 2");
    QLineEdit *setDemLine2 = new QLineEdit();
    QLineEdit *setAcLine2 = new QLineEdit();
    QPushButton *pushButton_2 = new QPushButton("2");
 
    QWidget *w3 = new QWidget;
    QVBoxLayout *logLayout = new QVBoxLayout;
    QTextEdit *logField = new QTextEdit;
 
    QWidget *as = new QWidget();
    ~MainWindow();
 
private:
    Ui::MainWindow *ui;
 
signals:
 
 
};
 
#endif // MAINWINDOW_H

acceleration.cpp:

Кликните здесь для просмотра всего текста

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include "acceleration.h"
 
 
 
Acceleration::Acceleration()
{
    dem = " ";
}
 
void Acceleration::SetDem(QLineEdit s)
{
    dem = s.text();
 
    if(dem != "м/сек^2" || dem != "км/сек^2" || dem != "фут/сек^2" || dem != "ярд/сек^2")
    {
        throw "Неверно введены единицы измерения";
    }
}
 
void Acceleration::SetDem(int a)
{
 
    if(a == 1)
    {
        dem = "м/сек^2";
    }
    if(a == 2)
    {
        dem = "км/сек^2";
    }
    if(a == 3)
    {
        dem = "фут/сек^2";
    }
    if(a == 4)
    {
        dem = "ярд/сек^2";
    }
    else
    {
        throw "Неверно введены единицы измерения";
    }
 
}
 
void Acceleration::Set(QString s)
{
    QString a = s.section(",", 0,0);
    acc = a.toFloat();
 
    dem = s.section(",", 1, 1);
}
 
void Acceleration::Set(float a, QString s)
{
    acc = a;
 
    dem = s;
}
 
void Acceleration::Set(float ac, int a)
{
    acc = ac;
 
    if(a == 1)
    {
        dem = "м/сек^2";
    }
    if(a == 2)
    {
        dem = "км/сек^2";
    }
    if(a == 3)
    {
        dem = "фут/сек^2";
    }
    if(a == 4)
    {
        dem = "ярд/сек^2";
    }
    else
    {
        throw "Неверно введены единицы измерения";
    }
}

mainwindow.cpp:

Кликните здесь для просмотра всего текста

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "acceleration.h"
 
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //First acceleration
    w1->setLayout(layoutFirstAc);
    layoutFirstAc->addWidget(setDem,1,0);
    layoutFirstAc->addWidget(setAc,2,0);
    layoutFirstAc->addWidget(firstAc,0,1);
    layoutFirstAc->addWidget(setDemLine1,1,1);
 
    layoutFirstAc->addWidget(setAcLine1,2,1);
    setDemLine1->setFixedSize(100,20);
    setAcLine1->setFixedSize(100,20);
    layoutFirstAc->addWidget(pushButton,3,1);
 
    //Second acceleration
    w2->setLayout(layoutSecondAc);
    layoutSecondAc->addWidget(secondAc,0,1);
    layoutSecondAc->addWidget(setDemLine2,1,1);
 
    layoutSecondAc->addWidget(setAcLine2,2,1);
    setDemLine2->setFixedSize(100,20);
    setAcLine2->setFixedSize(100,20);
    layoutSecondAc->addWidget(pushButton_2,3,1);
 
    w3->setLayout(logLayout);
    logLayout->addWidget(logField);
    logField->setReadOnly(true);
 
 
    mainLayout->addWidget(w1);
    mainLayout->addWidget(w2);
    mainLayout->addWidget(w3);
 
    as->setLayout(mainLayout);
 
    setCentralWidget(as);
 
    Acceleration first;
    Acceleration second;
 
   QObject::connect(pushButton, SIGNAL(clicked()), first, SLOT(Acceleration::Set(setAcLine1->text())));
 
 
}
 
MainWindow::~MainWindow()
{
    delete ui;
}

main.cpp:

Кликните здесь для просмотра всего текста

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
#include "mainwindow.h"
#include <QApplication>
#include "acceleration.h"
 
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
 
    return a.exec();
}



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

18.05.2018, 10:51

Ответы с готовыми решениями:

ошибка connect
Привет. Гляньте, пожалуйста, на скрин. Может сможете объяснить в чем ошибка, код всех файлов не…

Ошибка при connect
Доброй ночи.
Использую VS2010(Ultimate) + Qt libraries 4.8.3 for Windows (VS 2010, 235 MB) + Qt…

ошибка при connect()
Привет.

Я бы хотел что бы при нажатии на пункт меню m_system_action создавался виджет. С…

QObject::connect — ошибка
int main(int argc, char *argv)
{
QApplication a(argc, argv);
QWidget wgt;

10

Lolobotik

278 / 87 / 37

Регистрация: 10.06.2015

Сообщений: 261

18.05.2018, 11:26

2

Ну, во-первых, нельзя прямо в коннекте пихать в слот параметры. Параметры должны передаться сигналом. Если очень хочется, можно воткнуть лямбду на слот.
Во-вторых, (а ошибка, насколько я понял, именно из-за «во-вторых») у тебя метод Set перегружен несколько раз, поэтому connect не в курсе, к чему привязывать сигнал (к какой из перегруженных функций). Нужно явно указать (кастом), что за слот тебе нужен.
Примерно так:

C++ (Qt)
1
connect(pushButton, &QPushButton::clicked, first, static_cast<void (Acceleration::*)(QString )>(&Acceleration::Set))

Есть ещё вариант поновее (но суть та же):

C++ (Qt)
1
connect(pushButton, &QPushButton::clicked, first, qOverload<QString >(&Acceleration::Set))

НО
Как я уже написал, clicked не передаёт никаких параметров, а у слота их не может быть больше, чем у сигнала. Поэтому описываемая ощибка исчезнет, но появится новая. Тут либо лямбду вставлять, либо какую-то прослойку делать между clicked и Acceleration::Set.



0



rediculus

0 / 0 / 0

Регистрация: 23.04.2017

Сообщений: 9

18.05.2018, 11:49

 [ТС]

3

Попробовал добавить каст так, как вы показали.

C++ (Qt)
1
QObject::connect(pushButton, &QPushButton::clicked, first,static_cast<void (Acceleration::*)(QString)> (&Acceleration::Set));

Выдает вот это дело: ошибка: no matching function for call to ‘MainWindow::connect(QPushButton*&, void (QAbstractButton::*)(bool), Acceleration&, void (Acceleration::*)(QString))’
QObject::connect(pushButton, &QPushButton::clicked, first,static_cast<void (Acceleration::*)(QString)> (&Acceleration::Set));
Извините, если я сильно туплю, но в этом деле я пока не особенно силен.



0



278 / 87 / 37

Регистрация: 10.06.2015

Сообщений: 261

18.05.2018, 13:06

4

Я что-то впереди паровоза побежал. Не заметил, что у тебя first — не указатель. Нужно &first в коннекте писать. Просто у тебя всё как-то нагромоздилось в одном месте (в плане ошибок).

НО

Ещё раз напишу. Даже так, как я написал, работать не будет. У кнопки есть сигнал clicked с параметорм bool. У тебя нет перегруженного варианта слота Acceleration::Set, который бы принимал бы bool или был бы вообще без параметров. У слота не может быть больше аргументов, чем у сигнала. Разного типа аргументы у слота и сигнала тоже не могут быть (разве что там какое-то неявное приведение типов сам компилятор сделает, а ля quint32 в int).



0



rediculus

0 / 0 / 0

Регистрация: 23.04.2017

Сообщений: 9

18.05.2018, 16:36

 [ТС]

5

Заменил слот методом, который принимает параметр bool.

C++ (Qt)
1
QObject::connect(pushButton, &QPushButton::clicked, &first, &Acceleration::SetSlot(bool));

Метод объявил, реализацию прописал. Собственно, в нем вызываю другой метод.

C++ (Qt)
1
2
3
4
void Acceleration::SetSlot(bool a)
{
    Set(MainWindow::setDemLine1->text());
}

Опять жалуется на connect, только по-другому.
ошибка: expected primary-expression before ‘bool’
QObject::connect(&pushButton, &QPushButton::clicked, &first, &Acceleration::SetSlot(bool));



0



TRam_

зомбяк

1581 / 1215 / 345

Регистрация: 14.05.2017

Сообщений: 3,939

18.05.2018, 16:40

6

Цитата
Сообщение от rediculus
Посмотреть сообщение

Заменил слот методом, который принимает параметр bool.

Нельзя так брать адрес у функции класса. Можно только так:

C++ (Qt)
1
QObject::connect(pushButton, &QPushButton::clicked, &first, static_cast<void (Acceleration::*)(bool)> (&Acceleration::SetSlot));

или же старым синтаксисом:

C++ (Qt)
1
QObject::connect(pushButton, SIGNAL(clicked(bool)), &first, SLOT(SetSlot(bool)));



0



rediculus

0 / 0 / 0

Регистрация: 23.04.2017

Сообщений: 9

18.05.2018, 16:52

 [ТС]

7

Цитата
Сообщение от TRam_
Посмотреть сообщение

или же старым синтаксисом:

Старым синтаксисом переписал. Теперь на коннект не ругается.
Ругается на вот этот метод теперь:

Цитата
Сообщение от rediculus
Посмотреть сообщение

C++ (Qt)
1
2
3
4
void Acceleration::SetSlot(bool a)
{
Set(MainWindow::setDemLine1->text());
}

ошибка: invalid use of non-static data member ‘MainWindow::setDemLine1’
QLineEdit *setDemLine1 = new QLineEdit();
ошибка: from this location
Set(&MainWindow::setDemLine1->text());
Опять не понял, что не так ему.



0



Lolobotik

278 / 87 / 37

Регистрация: 10.06.2015

Сообщений: 261

18.05.2018, 17:08

8

Что-то всё не слава богу

Цитата
Сообщение от rediculus
Посмотреть сообщение

invalid use of non-static data member

Думаю эта строчка вполне себе гуглится, даже если не вдаваться в то, что она значит. Можно было и попробовать.
Ты дёргаешь поле класса не являющееся статическим. А его можно дёргать только непосредственно у экземпляра класса. Тобишь тебе нужно образаться не к «безстелесному», а к конкретному окну, и писать не МойКласс::Поле, а ОбъектмМоегоКласса.Поле, либо УказательНаОбъектМоегоКласса->Поле.
А вообще, сделай уже:

C++ (Qt)
1
2
    Acceleration *first = new Acceleration();
    QObject::connect(pushButton, &QPushButton::clicked,[=]{first->Set(setDemLine1->text());});

и не мучайся. Я не особо вникал, что ты собираешь потом с first делать, но у тебя он объявлен на стеке и как только конструктор MainWindow отработает — он удалится. Толку от коннекта будет мало.



1



0 / 0 / 0

Регистрация: 23.04.2017

Сообщений: 9

18.05.2018, 17:45

 [ТС]

9

Цитата
Сообщение от Lolobotik
Посмотреть сообщение

Думаю эта строчка вполне себе гуглится, даже если не вдаваться в то, что она значит.

Да я в целом понимаю разницу между статическими и не статическими полями, но сейчас уже совсем голова не варит что-то.

Цитата
Сообщение от Lolobotik
Посмотреть сообщение

А вообще, сделай уже:

Эта штука заработала, спасибо, я долго мучался.
Вот здесь я не до конца понял, что вы сделали, такого я не видел нигде.



0



278 / 87 / 37

Регистрация: 10.06.2015

Сообщений: 261

18.05.2018, 17:55

10

Лямбда, о которой я писал в самом первом посте.
С каких-то там пор можно коннекты вешать напрямую на них, вместо слотов.



0



0 / 0 / 0

Регистрация: 23.04.2017

Сообщений: 9

18.05.2018, 18:08

 [ТС]

11

А, так вот как это должно выглядеть, значит. А я после первого вашего поста начал гуглить и ничего толком не понял. Спасибо.



0



MyThread наследует QThread, w.getScene() возвращает указатель на объект класса Scene, унаследованный от QGraphicsScene

Создаю в main’e 2 коннекта:

#include <QtGui/QApplication>
#include «mainwindow.h»
#include <time.h>
#include «MyThread.h»
#include «Ship.h»
#include «Port.h»

int main(int argc, char *argv[])
{
    //Generating random number
    const time_t timer = time(NULL);
    tm *timerstruct = localtime(&timer);
    uint sec = timerstruct->tm_sec;
    qsrand(sec);
    int random = qrand()%3;

    QApplication a(argc, argv);
    MainWindow w;
    w.setFixedSize(550,600);
    w.show();

    Port* port = new Port;

    MyThread thread(random,port);

    QObject::connect(&thread,SIGNAL(shipMoves(Ship*,qreal)),w.getScene(),SLOT(moveShip(Ship*,qreal)));
    QObject::connect(&thread,SIGNAL(newShip(Ship*)),w.getScene(),SLOT(addNewShip(Ship*)));
    thread.start();

    return a.exec();
}

Получаю для каждого из коннектов

error: no matching function for call to ‘QObject::connect(MyThread*, const char*, Scene*, const char*)’
note: candidates are: static bool QObject::connect(const QObject*, const char*, const QObject*, const char*, Qt::ConnectionType)
note:                 bool QObject::connect(const QObject*, const char*, const char*, Qt::ConnectionType) const

в чём дело?

Hello,
I’m new to this forum and still pretty new to programming in general. I’m using C++ and Qt, trying to design a GUI app as an exercise.

I’m encountering the following error when I try to compile my code: no matching function for call to ‘QGridLayout::addWidget(QLabel, int, int)’.
I saw this thread: http://www.cplusplus.com/forum/beginner/22112/ regarding the same error, but after fiddling with my code (especially with * and &), I couldn’t fix this issue.

Here is the relevant code:
LabelArray.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <QtWidgets>

class LabelArray
{

public:
    LabelArray(int size);
    void setLabel(int index, QString text);
    QLabel getLabel(int index) const;

private:
    QVector<QLabel*> m_array;
    int m_size;
};

LabelArray.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include "LabelArray.h"

LabelArray::LabelArray(int size) : m_size(size), m_array(m_size, 0)
{
    for (int i=0; i<m_size; ++i)
    {
        m_array[i] = new QLabel(QString("Label")+ i);
    }
}
void LabelArray::setLabel(int index, QString text)
{
    m_array[index]->setText(text);
}
QLabel LabelArray::getLabel(int index) const
{
    return m_array[index];
}

Initializing the QLabel array and trying to add each of its QLabel to the layout. This code is from file PlanetsData.cpp, PlanetsData being a custom class inheriting QWidget.
Also, in PlanetsData.h, I have LabelArray *pLabelsL as private:

1
2
3
4
5
6
7
8
9
10
11
12
//Create a QLabel array
pLabelsL = new LabelArray(pParameters);
updatePlanetsData(0);
for (int i=0; i<pParameters; ++i)
{
    pLabelsL[i].setLabel(i, pIndexedData->getData(i));
}
//Add each QLabel from the array to the layout
for (int i=1; i<pParameters; ++i)
{
    pDataLayout->addWidget(pLabelsL->getLabel(i), i-1, 0);
}

The error happens at line 11.

I’ve tried replacing the getLabel(int) method with the [] operator (pLabelsL[i] instead of pLabelsL->getLabel(i)) to try and make sure the issue wasn’t there.
I also tried returning a QLabel& from this method, creating a QLabel &label in the last for loop to return that instead, but to no avail (I only managed to turn the error to (QLabel&, int, int) instead of (QLabel, int, int)).

If anyone would be so kind as to help me find the issue?
I don’t think I need to post the code for the PlanetsData class, but I can add it if needed.
Many thanks in advance!

Edit: I’m noticing several «unimportant» variables/functions that might need explaining:
pParameters is an integer defined earlier in PlanetsData.cpp
updatePlanetsData() is a method of PlanetsData and updates data in an Array1D object
pIndexedData is an Array1D object (basically a QString array)

Last edited on

I suppose the obvious question is: have you defined the function QGridLayout::addWidget(QLabel, int, int) ?

In the small snippets of code shared above, I can’t see it. In fact I don’t see any of the code for QGridLayout. I don’t think there is enough information here to give a more detailed answer.

Heh, sorry I haven’t given more details about this.
Actually, QGridLayout (included in <QtWidgets> ) is a Qt type, so pLabelsL is a QGridLayout.
QGridLayout::addWidget takes 3 parameters: (QWidget, int, int).
QLabel inherits from QWidget, and I’ve had no trouble adding other QWidget objects in other places in the code.

The issue really seems to come from my LabelArray class.

I just had an idea, and will try to avoid using LabelArray at all in the mean time.
The reason I used it was to avoid having to define an array in PlanetsData.h, but I’m thinking that defining a vector might help.
I will experiment with this and see if it can help me solve my issue.

My mistake, I forgot that you were using the external Qt library. As you might have guessed, I’m not really familiar with that. Maybe someone else who is familiar with Qt could give a better response.

Qt has online (and local) documentation. The version that I did peek does offer a QGridLayout::addWidget(QWidget *, int, int). A pointer. Not a reference nor a by-value copy; QObjects are not copyable.

QGridLayout::addWidget takes 3 parameters: (QWidget, int, int).

Are you sure that’s true? It’s been a long time since I did any QT, but I’m pretty certain that first argument should be a QWidget*. It would be really weird if it was taking an object by parameter, i.e. copying the class.

Last edited on

Yes, my bad, I was passing pointers without really realizing.

I ended up getting rid of the QVector<QLabel*> for my LabelArray class, and used a QList<QLabel*> instead; I find it much easier to use, and I actually got the code to compile and execute as expected.
Here is the code that I used:

1
2
3
4
5
6
7
8
9
10
11
12
13
//LabelArray.h
class LabelArray
{

public:
    LabelArray(int size);
    void setLabel(int index, QString text);
    QLabel* getLabel(int index) const; // This function now returns a QLabel*

private:
    QList<QLabel*> m_list;
    int m_size;
};

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//LabelArray.cpp
#include "LabelArray.h"

LabelArray::LabelArray(int size) : m_size(size)
{
    for (int i=0; i<m_size; ++i)
    {
        m_list << new QLabel(QString("Label")+ i);
    }
}
void LabelArray::setLabel(int index, QString text)
{
    m_list.at(index)->setText(text);
}
QLabel* LabelArray::getLabel(int index) const
{
    return m_list.at(index);
}

In PlanetsData.h, I have: LabelArray *pLabelsR;

1
2
3
4
5
6
7
//This is the part that uses LabelArray in PlanetsData.cpp
    pLabelsR = new LabelArray(pParameters);
    updatePlanetsData(1);
    for (int i=0; i<pParameters; ++i)
    {
        pLabelsR->setLabel(i, pIndexedData->getData(i));
    }

LabelArray::getLabel was previously returning a QLabel, but even when I tried to return a QLabel*, another error would pop up. Using a QList, I managed to return a QLabel* without difficulty (was probably another mistake on my end).

Now I have to make sure the QLabel objects update when needed, but that’s another story entirely.

Thanks everyone for your help and pointing out my mistake in the addWidget function!
I’ll make sure I remember that for future reference.

Last edited on


0

1

Пишу так:

class Parent {
public:
	virtual void someSignal() = 0;
};

class Child: public QObject, public Parent {
	Q_OBJECT
public signals:
	void someSignal() {}
};
Parent *pointer = getPointer();

connect(pointer, SIGNAL(someSignal), this, SLOT(someSlot())); // первый
connect(qobject_cast<QObject*>(pointer), SIGNAL(someSignal), this, SLOT(someSlot())); // второй

Первый вариант падает с

error: no matching function for call to 'Shooter::connect(Parent*&, const char*, Shooter* const, const char*)'
note:  no known conversion for argument 1 from 'Parent*' to 'const QObject*'

Подумав и погуглив понял что надо приводить к QObject, но не помогает, второй вариант тоже не работает:

error: no matching function for call to 'qobject_cast(Parent*&)'
note:  candidates are: template<class T> T qobject_cast(QObject*)

А здесь мне уже не понятно, указатель ведь указывает на потомка, а его можно легко привести к QObject. Почему тогда так?

Понравилась статья? Поделить с друзьями:
  • Ошибка no more mirrors to try
  • Ошибка no matching distribution found for
  • Ошибка no module named pandas
  • Ошибка no match for operator operand types are std
  • Ошибка no module named numpy