I would like to make a simple QT mainwindow with the button to open a second window or dialog. I followed literally the step from the QT link «Using a Designer UI File in Your Application» and following the single inheritance example.
But QT gives 4 errors , which you will see a snapshot of below.
Now, what I did is I created a mainwindow in Qt designer, then I added a second form to the project , which will be the second dialog window when a button clicked. Because I created the form manually «mydialog.ui», I added class «mydialog.h and mydialog.cpp» and put the header of «ui-mydialog» in the source file «mydialog.cpp».
I’ not sure what am I missing ?
Below is the code :
— mydialog.h
#ifndef MYDIALOG_H
#define MYDIALOG_H
#include<QWidget>
class mydialog ;
namespace Ui {
class mydialog;
}
class mydialog : public QWidget
{
Q_OBJECT
public:
explicit mydialog(QWidget *parent = 0);
virtual ~mydialog();
private :
Ui::mydialog *ui;
};
#endif // MYDIALOG_H
— mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QtCore/QtGlobal>
#include <QMainWindow>
QT_USE_NAMESPACE
QT_BEGIN_NAMESPACE
namespace Ui {
class MainWindow;
}
QT_END_NAMESPACE
class mydialog;
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_Start_clicked();
private:
Ui::MainWindow *ui;
mydialog *dialog1;
};
#endif // MAINWINDOW_H
— mydialog.cpp
#include"mydialog.h"
#include "ui_mydialog.h"
mydialog::mydialog(QWidget *parent) : QWidget(parent), ui(new Ui::mydialog)
{
ui->setupUi(this);
}
mydialog::~mydialog()
{
delete ui;
}
— mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include"mydialog.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
dialog1 = new mydialog ;
}
MainWindow::~MainWindow()
{
delete ui;
delete dialog1;
}
void MainWindow::on_Start_clicked()
{
}
— main.cpp
#include"mainwindow.h"
#include<QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
— The .pro file
#-------------------------------------------------
#
# Project created by QtCreator 2015-12-17T00:10:58
#
#-------------------------------------------------
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = TestTool
TEMPLATE = app
SOURCES += main.cpp
mainwindow.cpp
mydialog.cpp
HEADERS += mainwindow.h
mydialog.h
FORMS += mainwindow.ui
mydialog.ui
RESOURCES +=
misc.qrc
— Qt compilation output error
Compilation error
The generated file Ui_mydialog.h is :
#ifndef UI_MYDIALOG_H
#define UI_MYDIALOG_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QDialog>
#include <QtWidgets/QDialogButtonBox>
#include <QtWidgets/QHeaderView>
QT_BEGIN_NAMESPACE
class Ui_Dialog
{
public:
QDialogButtonBox *buttonBox;
void setupUi(QDialog *Dialog)
{
if (Dialog->objectName().isEmpty())
Dialog->setObjectName(QStringLiteral("Dialog"));
Dialog->resize(400, 300);
buttonBox = new QDialogButtonBox(Dialog);
buttonBox->setObjectName(QStringLiteral("buttonBox"));
buttonBox->setGeometry(QRect(30, 240, 341, 32));
buttonBox->setOrientation(Qt::Horizontal);
buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok);
retranslateUi(Dialog);
QObject::connect(buttonBox, SIGNAL(accepted()), Dialog, SLOT(accept()));
QObject::connect(buttonBox, SIGNAL(rejected()), Dialog, SLOT(reject()));
QMetaObject::connectSlotsByName(Dialog);
} // setupUi
void retranslateUi(QDialog *Dialog)
{
Dialog->setWindowTitle(QApplication::translate("Dialog", "Dialog", 0));
} // retranslateUi
};
namespace Ui {
class Dialog: public Ui_Dialog {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_MYDIALOG_H
Update: Forum Guidelines & Code of Conduct
Qt World Summit: Early-Bird Tickets
This topic has been deleted. Only users with topic management privileges can see it.
-
C:UsersLorence30Desktoptestmainwindow.h:32: error: invalid use of incomplete type ‘class Ui::MainWindow’ ui->grassyTile
^why i keep getting this error?
I have my Q_OBJECT macro inside the MainWindow class.
*[link text](link url) class MainWindow : public QMainWindow
{
Q_OBJECTpublic:
explic[it MainWindow(QWidget *parent = 0);
~MainWindow();](link url)private slots:
void changeTile();
void pushTile();private:
Ui::MainWindow *ui;
int counter;std::array<Tile,1> tile_list { ui->grassyTile // heres where error coming from };
};
-
@Lorence said:
grassyTile
What type is that ?
«use of incomplete type» often means a include file is missing
or you forwarded a class
like
class SomeClass;And try to use it in a context where it needs to be fully defined.
Like adding to some template lists.Not sure what you tried to define here ?
std::array<Tile,1> tile_list <—- ; missing here?
{
ui->grassyTile // heres where error coming from
}; -
grassyTile is of type Tile that is inheriting QLabel
Not sure what you tried to define here ?
i dont know how to list intialize an array on constructor so i decided to do it in side a class definition -
@mrjj said:
and «tile.h» is included ?
in mainwindow.hdo you mean like ?
std::array<std::string, 2> strings = {{ «a», «b» }}; -
and «tile.h» is included ?
yes i got all i need included.
do you mean like ?
std::array<std::string, 2> strings = {{ «a», «b» }};yes, in the mainwindow.cpp i can freely use ui->grassyTile; without error.
-
@Lorence
Ok so it must be the tile_list statement.Would it like
std::array<Tile,1> tile_list {{ui->grassyTile }}; -
Would it like
std::array<Tile,1> tile_list {{ui->grassyTile }};thanks for the help but i still get the same error
-
@Lorence
Ok, and you are 100% it knows the tile type here?
you can declare one over the tile_list and it will like it ?
Tile *Test;One thing I wonder, you say
std::array<Tile> and not std::array<Tile *) or & so it must make a copy of
it (the tile). Is that the effect you want? -
@Lorence
Hmm it seems its «ui» it do not like.
Let me test. -
@mrjj
ahh, Ui::MainWindow is defined in
#include «ui_main_window.h»
which is included in the CPP file so the type is not fully defined so you cannot say
ui->Somename
as Ui::MainWindow is not defined yet.moving
#include «ui_main_window.h»
to the minwin.h file allows it but not sure if it will confuse Qt Creator.Also it will complain about not being able to convert Tile to Tile * as list is not pointers and ui->grassyTile will be.
-
ahh, Ui::MainWindow is defined in
#include «ui_main_window.h»didnt think of that, thanks! but new error comes
-
@Lorence
Yeah, it tries to construct a new Tile to go into the list.
Can I ask if you want a list of pointers to tiles you have on screen or
a list with new Tiles that has nothing to do with those on screen? -
sorry for the late reply.
i just want a list of tiles to choose from.
but QT disabled the copying of QLabel,
so i really need to have a pointer of tiles? -
@Lorence
heh 9 mins is not considered latethen the list must be pointer type or it will be new ones and not the ones on screen.
so
std::array<Tile> should be std::array<Tile *> or std::array<Tile &>
so its the ones on screen and not new ones
Yes you must at least use & as it must «point» to the real one. -
then the list must be pointer type
yea, i edited my last replyit will be new ones and not the ones on screen.
it is the ones on the screen, there will be a list of tiles on the screen and the user will choose what tiles they want to render
*so
std::array<Tile> should be std::array<Tile > or std::array<Tile &>
so its the ones on screen and not new ones
Yes you must at least use & as it must «point» to the real one.thanks!!!!!!!!
all my problem is fixed I have not coded for weeks and C++ is already kicking me damit
-
@mrjj said:
ok. Superand tile_list is the ones to choose from ?
Dont worry. I programmed c++ for 20 years and it still kicks me
-
and tile_list is the ones to choose from ?
yes, it is a list of Tile which is inheriting QLabel
Dont worry. I programmed c++ for 20 years and it still kicks me
woaaaaa, me is about a year, and started this QT last week, i choose this for my tile engine’s interface from SFML, i still have more ways to go !^_^
-
@Lorence said:
welcome on board to Qt. its a nice frame work.Oh so its some sort of game editor your are making ?
-
welcome on board to Qt. its a nice frame work.
Yes my first choice is wxwidget and windows form application, but signals and slots mechanism of qt makes me decide to choose qt
Oh so its some sort of game editor your are making ?
yes exatcly, like the rpg maker vx ace of steam
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 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 |
#include "dialogadddevice.h" #include "ui_dialogadddevice.h" DialogAddDevice::DialogAddDevice(int row, QWidget *parent) : QDialog(parent), ui(new Ui::DialogAddDevice) { ui->setupUi(this); /* Метода для инициализации модели, * из которой будут транслироваться данные * */ setupModel(); /* Если строка не задана, то есть равна -1, * тогда диалог работает по принципу создания новой записи. * А именно, в модель вставляется новая строка и работа ведётся с ней. * */ if(row == -1){ model->insertRow(model->rowCount(QModelIndex())); mapper->toLast(); /* В противном случае диалог настраивается на заданную запись * */ } else { mapper->setCurrentModelIndex(model->index(row,0)); } createUI(); } DialogAddDevice::~DialogAddDevice() { delete ui; } /* Метод настройки модели данных и mapper * */ void DialogAddDevice::setupModel() { /* Инициализируем модель и делаем выборку из неё * */ model = new QSqlTableModel(this); model->setTable(DEVICE); model->setEditStrategy(QSqlTableModel::OnManualSubmit); model->select(); /* Инициализируем mapper и привязываем * поля данных к объектам LineEdit * */ mapper = new QDataWidgetMapper(); mapper->setModel(model); mapper->addMapping(ui->HostnameLineEdit, 1); mapper->addMapping(ui->IPAddressLineEdit, 2); mapper->addMapping(ui->MACLineEdit, 3); /* Ручное подтверждение изменения данных * через mapper * */ mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); /* Подключаем коннекты от кнопок пролистывания * к прилистыванию модели данных в mapper * */ connect(ui->previousButton, SIGNAL(clicked()), mapper, SLOT(toPrevious())); connect(ui->nextButton, SIGNAL(clicked()), mapper, SLOT(toNext())); /* При изменении индекса в mapper изменяем состояние кнопок * */ connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(updateButtons(int))); } /* Метод для установки валидатора на поле ввода IP и MAC адресов * */ void DialogAddDevice::createUI() { QString ipRange = "(?:[0-1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])"; QRegExp ipRegex ("^" + ipRange + "\." + ipRange + "\." + ipRange + "\." + ipRange + "$"); QRegExpValidator *ipValidator = new QRegExpValidator(ipRegex, this); ui->IPAddressLineEdit->setValidator(ipValidator); QString macRange = "(?:[0-9A-Fa-f][0-9A-Fa-f])"; QRegExp macRegex ("^" + macRange + "\:" + macRange + "\:" + macRange + "\:" + macRange + "\:" + macRange + "\:" + macRange + "$"); QRegExpValidator *macValidator = new QRegExpValidator(macRegex, this); ui->MACLineEdit->setValidator(macValidator); } void DialogAddDevice::on_buttonBox_accepted() { /* SQL-запрос для проверки существования записи * с такими же учетными данными. * Если запись не существует или находится лишь индекс * редактируемой в данный момент записи, * то диалог позволяет вставку записи в таблицу данных * */ QSqlQuery query; QString str = QString("SELECT EXISTS (SELECT " DEVICE_HOSTNAME " FROM " DEVICE " WHERE ( " DEVICE_HOSTNAME " = '%1' " " OR " DEVICE_IP " = '%2' )" " AND id NOT LIKE '%3' )") .arg(ui->HostnameLineEdit->text(), ui->IPAddressLineEdit->text(), model->data(model->index(mapper->currentIndex(),0), Qt::DisplayRole).toString()); query.prepare(str); query.exec(); query.next(); /* Если запись существует, то диалог вызывает * предупредительное сообщение * */ if(query.value(0) != 0){ QMessageBox::information(this, trUtf8("Ошибка хоста"), trUtf8("Хост с таким именем или IP-адресом уже существует")); /* В противном случае производится вставка новых данных в таблицу * и диалог завершается с передачей сигнала для обновления * таблицы в главном окне * */ } else { mapper->submit(); model->submitAll(); emit signalReady(); this->close(); } } void DialogAddDevice::accept() { } /* Метод изменения состояния активности кнопок пролистывания * */ void DialogAddDevice::updateButtons(int row) { /* В том случае, если мы достигаем одного из крайних (самый первый или * самый последний) из индексов в таблице данных, * то мы изменяем состояние соответствующей кнопки на * состояние неактивна * */ ui->previousButton->setEnabled(row > 0); ui->nextButton->setEnabled(row < model->rowCount() - 1); } |
Автор | Тема: invalid use of incomplete type (решено) (Прочитано 25272 раз) |
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
- Forum
- Beginners
- Invalid use of incomplete type
Invalid use of incomplete type
I get these errors i dont have any idea how to solve.
I have searched Goolge and StackOverflow and found stuff related to this but i couldn’t solve this.
Any help is much appreciated.
error: invalid use of incomplete type ‘class Ui::AddDialog’
error: forward declaration of ‘class Ui::AddDialog’
addDialog.h
|
|
AddDialog.cpp
|
|
gpa.h
|
|
gpa.cpp
|
|
How does «ui_addDialog.h» look like?
its a form. Im programming with Qt
Why are the errors only for AddDialog
when AddDialog
has the same structure as Gpa
Last edited on
ui_AddDialog is generated by Qt Creator.
Make sure you made AddDialog with Qt Creator.
Also try doing a clean build.
I have done the clean build but no change.
Yes i made AddDialog with QtCreator.
I then added the header and .cpp files manually instead of them being generated automatically as it was with Gpa.
But I think Gpa files were automatically generated becauase Gpa is my main project.
I fixed the issue.
I selected Designer form file instead of Designer form class when creating the AddDialog form.
Topic archived. No new replies allowed.