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*)’ Connect писал как в main.cpp, так и в mainwindow.cpp, везде одно и то же. Сейчас он в mainwindow.cpp. Долго искал в чем проблема, рылся по форумам, решение не нашел. Acceleration.h: Кликните здесь для просмотра всего текста
mainwindow.h: Кликните здесь для просмотра всего текста
acceleration.cpp: Кликните здесь для просмотра всего текста
mainwindow.cpp: Кликните здесь для просмотра всего текста
main.cpp: Кликните здесь для просмотра всего текста
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
18.05.2018, 10:51 |
Ответы с готовыми решениями:
Ошибка при connect ошибка при connect() Я бы хотел что бы при нажатии на пункт меню m_system_action создавался виджет. С… QObject::connect — ошибка 10 |
Lolobotik 278 / 87 / 37 Регистрация: 10.06.2015 Сообщений: 261 |
||||||||
18.05.2018, 11:26 |
2 |
|||||||
Ну, во-первых, нельзя прямо в коннекте пихать в слот параметры. Параметры должны передаться сигналом. Если очень хочется, можно воткнуть лямбду на слот.
Есть ещё вариант поновее (но суть та же):
НО
0 |
rediculus 0 / 0 / 0 Регистрация: 23.04.2017 Сообщений: 9 |
||||
18.05.2018, 11:49 [ТС] |
3 |
|||
Попробовал добавить каст так, как вы показали.
Выдает вот это дело: ошибка: no matching function for call to ‘MainWindow::connect(QPushButton*&, void (QAbstractButton::*)(bool), Acceleration&, void (Acceleration::*)(QString))’
0 |
278 / 87 / 37 Регистрация: 10.06.2015 Сообщений: 261 |
|
18.05.2018, 13:06 |
4 |
Я что-то впереди паровоза побежал. Не заметил, что у тебя first — не указатель. Нужно &first в коннекте писать. Просто у тебя всё как-то нагромоздилось в одном месте (в плане ошибок).
0 |
rediculus 0 / 0 / 0 Регистрация: 23.04.2017 Сообщений: 9 |
||||||||
18.05.2018, 16:36 [ТС] |
5 |
|||||||
Заменил слот методом, который принимает параметр bool.
Метод объявил, реализацию прописал. Собственно, в нем вызываю другой метод.
Опять жалуется на connect, только по-другому.
0 |
TRam_ зомбяк 1581 / 1215 / 345 Регистрация: 14.05.2017 Сообщений: 3,939 |
||||||||
18.05.2018, 16:40 |
6 |
|||||||
Заменил слот методом, который принимает параметр bool. Нельзя так брать адрес у функции класса. Можно только так:
или же старым синтаксисом:
0 |
rediculus 0 / 0 / 0 Регистрация: 23.04.2017 Сообщений: 9 |
||||
18.05.2018, 16:52 [ТС] |
7 |
|||
или же старым синтаксисом: Старым синтаксисом переписал. Теперь на коннект не ругается.
ошибка: invalid use of non-static data member ‘MainWindow::setDemLine1’
0 |
Lolobotik 278 / 87 / 37 Регистрация: 10.06.2015 Сообщений: 261 |
||||
18.05.2018, 17:08 |
8 |
|||
Что-то всё не слава богу
invalid use of non-static data member Думаю эта строчка вполне себе гуглится, даже если не вдаваться в то, что она значит. Можно было и попробовать.
и не мучайся. Я не особо вникал, что ты собираешь потом с first делать, но у тебя он объявлен на стеке и как только конструктор MainWindow отработает — он удалится. Толку от коннекта будет мало.
1 |
0 / 0 / 0 Регистрация: 23.04.2017 Сообщений: 9 |
|
18.05.2018, 17:45 [ТС] |
9 |
Думаю эта строчка вполне себе гуглится, даже если не вдаваться в то, что она значит. Да я в целом понимаю разницу между статическими и не статическими полями, но сейчас уже совсем голова не варит что-то.
А вообще, сделай уже: Эта штука заработала, спасибо, я долго мучался.
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
|
|
LabelArray.cpp
|
|
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:
|
|
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:
|
|
|
|
In PlanetsData.h, I have: LabelArray *pLabelsR;
|
|
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. Почему тогда так?