|
Автор | Тема: Не работает Hello World! (Прочитано 14138 раз) |
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
ok, the main.cpp is at https://qt-project.org/doc/qt-4.7/desktop-systray-window-cpp.html, which i’ll repost below for clarity.
I’m thinking that this might be a versioning issue, where this demo was written in qt-4.7 and ubuntu’s qtcreator is trying to compile it at qt-5.
How do I tell qtcreator to compile this project with qt-4.7?
/************************************************** **************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** «Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
** the names of its contributors may be used to endorse or promote
** products derived from this software without specific prior written
** permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** «AS IS» AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.»
** $QT_END_LICENSE$
**
************************************************** **************************/
#include <QtGui>
#include «window.h»
Window::Window()
{
createIconGroupBox();
createMessageGroupBox();
iconLabel->setMinimumWidth(durationLabel->sizeHint().width());
createActions();
createTrayIcon();
connect(showMessageButton, SIGNAL(clicked()), this, SLOT(showMessage()));
connect(showIconCheckBox, SIGNAL(toggled(bool)),
trayIcon, SLOT(setVisible(bool)));
connect(iconComboBox, SIGNAL(currentIndexChanged(int)),
this, SLOT(setIcon(int)));
connect(trayIcon, SIGNAL(messageClicked()), this, SLOT(messageClicked()));
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason )),
this, SLOT(iconActivated(QSystemTrayIcon::ActivationReas on)));
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(iconGroupBox);
mainLayout->addWidget(messageGroupBox);
setLayout(mainLayout);
iconComboBox->setCurrentIndex(1);
trayIcon->show();
setWindowTitle(tr(«Systray»));
resize(400, 300);
}
void Window::setVisible(bool visible)
{
minimizeAction->setEnabled(visible);
maximizeAction->setEnabled(!isMaximized());
restoreAction->setEnabled(isMaximized() || !visible);
QDialog::setVisible(visible);
}
void Window::closeEvent(QCloseEvent *event)
{
if (trayIcon->isVisible()) {
QMessageBox::information(this, tr(«Systray»),
tr(«The program will keep running in the «
«system tray. To terminate the program, «
«choose <b>Quit</b> in the context menu «
«of the system tray entry.»));
hide();
event->ignore();
}
}
void Window::setIcon(int index)
{
QIcon icon = iconComboBox->itemIcon(index);
trayIcon->setIcon(icon);
setWindowIcon(icon);
trayIcon->setToolTip(iconComboBox->itemText(index));
}
void Window::iconActivated(QSystemTrayIcon::ActivationR eason reason)
{
switch (reason) {
case QSystemTrayIcon::Trigger:
case QSystemTrayIcon::DoubleClick:
iconComboBox->setCurrentIndex((iconComboBox->currentIndex() + 1)
% iconComboBox->count());
break;
case QSystemTrayIcon::MiddleClick:
showMessage();
break;
default:
;
}
}
void Window::showMessage()
{
QSystemTrayIcon::MessageIcon icon = QSystemTrayIcon::MessageIcon(
typeComboBox->itemData(typeComboBox->currentIndex()).toInt());
trayIcon->showMessage(titleEdit->text(), bodyEdit->toPlainText(), icon,
durationSpinBox->value() * 1000);
}
void Window::messageClicked()
{
QMessageBox::information(0, tr(«Systray»),
tr(«Sorry, I already gave what help I could.n»
«Maybe you should try asking a human?»));
}
void Window::createIconGroupBox()
{
iconGroupBox = new QGroupBox(tr(«Tray Icon»));
iconLabel = new QLabel(«Icon:»);
iconComboBox = new QComboBox;
iconComboBox->addItem(QIcon(«:/images/bad.svg»), tr(«Bad»));
iconComboBox->addItem(QIcon(«:/images/heart.svg»), tr(«Heart»));
iconComboBox->addItem(QIcon(«:/images/trash.svg»), tr(«Trash»));
showIconCheckBox = new QCheckBox(tr(«Show icon»));
showIconCheckBox->setChecked(true);
QHBoxLayout *iconLayout = new QHBoxLayout;
iconLayout->addWidget(iconLabel);
iconLayout->addWidget(iconComboBox);
iconLayout->addStretch();
iconLayout->addWidget(showIconCheckBox);
iconGroupBox->setLayout(iconLayout);
}
void Window::createMessageGroupBox()
{
messageGroupBox = new QGroupBox(tr(«Balloon Message»));
typeLabel = new QLabel(tr(«Type:»));
typeComboBox = new QComboBox;
typeComboBox->addItem(tr(«None»), QSystemTrayIcon::NoIcon);
typeComboBox->addItem(style()->standardIcon(
QStyle::SP_MessageBoxInformation), tr(«Information»),
QSystemTrayIcon::Information);
typeComboBox->addItem(style()->standardIcon(
QStyle::SP_MessageBoxWarning), tr(«Warning»),
QSystemTrayIcon::Warning);
typeComboBox->addItem(style()->standardIcon(
QStyle::SP_MessageBoxCritical), tr(«Critical»),
QSystemTrayIcon::Critical);
typeComboBox->setCurrentIndex(1);
durationLabel = new QLabel(tr(«Duration:»));
durationSpinBox = new QSpinBox;
durationSpinBox->setRange(5, 60);
durationSpinBox->setSuffix(» s»);
durationSpinBox->setValue(15);
durationWarningLabel = new QLabel(tr(«(some systems might ignore this «
«hint)»));
durationWarningLabel->setIndent(10);
titleLabel = new QLabel(tr(«Title:»));
titleEdit = new QLineEdit(tr(«Cannot connect to network»));
bodyLabel = new QLabel(tr(«Body:»));
bodyEdit = new QTextEdit;
bodyEdit->setPlainText(tr(«Don’t believe me. Honestly, I don’t have a «
«clue.nClick this balloon for details.»));
showMessageButton = new QPushButton(tr(«Show Message»));
showMessageButton->setDefault(true);
QGridLayout *messageLayout = new QGridLayout;
messageLayout->addWidget(typeLabel, 0, 0);
messageLayout->addWidget(typeComboBox, 0, 1, 1, 2);
messageLayout->addWidget(durationLabel, 1, 0);
messageLayout->addWidget(durationSpinBox, 1, 1);
messageLayout->addWidget(durationWarningLabel, 1, 2, 1, 3);
messageLayout->addWidget(titleLabel, 2, 0);
messageLayout->addWidget(titleEdit, 2, 1, 1, 4);
messageLayout->addWidget(bodyLabel, 3, 0);
messageLayout->addWidget(bodyEdit, 3, 1, 2, 4);
messageLayout->addWidget(showMessageButton, 5, 4);
messageLayout->setColumnStretch(3, 1);
messageLayout->setRowStretch(4, 1);
messageGroupBox->setLayout(messageLayout);
}
void Window::createActions()
{
minimizeAction = new QAction(tr(«Mi&nimize»), this);
connect(minimizeAction, SIGNAL(triggered()), this, SLOT(hide()));
maximizeAction = new QAction(tr(«Ma&ximize»), this);
connect(maximizeAction, SIGNAL(triggered()), this, SLOT(showMaximized()));
restoreAction = new QAction(tr(«&Restore»), this);
connect(restoreAction, SIGNAL(triggered()), this, SLOT(showNormal()));
quitAction = new QAction(tr(«&Quit»), this);
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
}
void Window::createTrayIcon()
{
trayIconMenu = new QMenu(this);
trayIconMenu->addAction(minimizeAction);
trayIconMenu->addAction(maximizeAction);
trayIconMenu->addAction(restoreAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);
trayIcon = new QSystemTrayIcon(this);
trayIcon->setContextMenu(trayIconMenu);
}
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Open
w5688414 opened this issue
Feb 14, 2019
· 2 comments
Comments
when i use make command, the error occurs:
src/main.cpp:16:18: error: variable has incomplete type 'QApplication' QApplication a(argc, argv); ^ /anaconda/include/qt/QtCore/qobject.h:453:18: note: forward declaration of 'QApplication' friend class QApplication; ^ src/main.cpp:45:13: error: use of undeclared identifier 'QMessageBox' QMessageBox::critical(0, ^ src/main.cpp:50:9: error: incomplete type 'QApplication' named in nested name specifier QApplication::setQuitOnLastWindowClosed(false); ^~~~~~~~~~~~~~ /anaconda/include/qt/QtCore/qobject.h:453:18: note: forward declaration of 'QApplication' friend class QApplication; ^ 3 errors generated. make: *** [main.o] Error 1
dmatetelki
pushed a commit
that referenced
this issue
Feb 15, 2019
Fixes #1
Is it a Qt5 issue?
#include <QApplication> #include <QMessageBox>
need to add QMessageBox as well.
it can run normally, but I can’t draw, all operations don’t work
2 participants
Переменная с ++ имеет инициализатор, но неполный тип?
Я пытаюсь скомпилировать 2 класса на C ++ с помощью следующей команды:
g++ Cat.cpp Cat_main.cpp -o Cat
Но я получаю следующую ошибку:
Cat.cpp:10:10: error: variable ‘Cat Joey’ has initializer but incomplete type
Может кто-нибудь объяснить мне, что это значит? В основном мои файлы создают класс (Cat.cpp
) и создайте экземпляр (Cat_main.cpp
). Вот мой исходный код:
Кат.cpp:
#include <iostream>
#include <string>
class Cat;
using namespace std;
int main()
{
Cat Joey("Joey");
Joey.Meow();
return 0;
}
Cat_main.cpp:
#include <iostream>
#include <string>
using namespace std;
class Cat
{
public:
Cat(string str);
// Variables
string name;
// Functions
void Meow();
};
Cat::Cat(string str)
{
this->name = str;
}
void Cat::Meow()
{
cout << "Meow!" << endl;
return;
}
Вы используете форвардное объявление, когда вам нужен полный тип.
У вас должно быть полное определение класса, чтобы использовать его.
Обычный способ сделать это:
1) создать файл Cat_main.h
2) move (двигаться)
#include <string>
class Cat
{
public:
Cat(std::string str);
// Variables
std::string name;
// Functions
void Meow();
};
в Cat_main.h
. Обратите внимание, что внутри заголовка я удалил using namespace std;
и квалифицированная строка с std::string
.
3) включите этот файл в оба Cat_main.cpp
и Cat.cpp
:
#include "Cat_main.h"
ответ дан 26 окт ’17, 20:10
Это не связано напрямую с делом Кена, но такая ошибка также может возникнуть, если вы скопировали .h файл и забыл изменить #ifndef
директива. В этом случае компилятор просто пропустит определение класса, думая, что это дублирование.
ответ дан 27 авг.
Иногда, та же ошибка возникает, когда вы forget to include the corresponding header
.
ответ дан 01 авг.
Вы не можете определить переменную неполного типа. Вам нужно принести полное определение Cat
в сферу до вы можете создать локальную переменную в main
. Рекомендую переместить определение типа Cat
в заголовок и включить его из единицы перевода, которая имеет main
.
ответ дан 19 мар ’12, в 13:03
Я получил аналогичную ошибку и попал на эту страницу во время поиска решения.
В Qt эта ошибка может произойти, если вы забудете добавить QT_WRAP_CPP( ... )
шаг в вашей сборке для запуска компилятора метаобъектов (moc). Включение заголовка Qt недостаточно.
ответ дан 27 авг.
Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками
c++
class
compiler-construction
or задайте свой вопрос.