What is wrong with the code bellow? When I compile it I get a warning that file not found. Something is invalid. I'm probably making a few mistakes here. I think the problem is perhaps with the way I inherit from QWidget.
#include <QtGui/QApplication>
#include "filedialogs.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
FileDialogs w;
w.openFile();
return 0;
}
#ifndef FILEDIALOGS_H
#define FILEDIALOGS_H
#include <QWidget>
class QFileDialog;
class FileDialogs : public QWidget
{
public:
FileDialogs(QWidget *parent = 0);
~FileDialogs();
void openFile();
};
#endif // FILEDIALOGS_H
#include <QFileDialog>
#include "filedialogs.h"
FileDialogs::FileDialogs(QWidget *parent)
: QWidget(parent)
{
}
FileDialogs::~FileDialogs()
{
}
void FileDialogs::openFile()
{
QString filename = QFileDialog::getOpenFileName(
this,
tr("Open Document"),
QDir::currentPath(),
tr("Document files (*.doc *.rtf);;All files (*.*)") );
if( !filename.isNull() )
{
qDebug( filename.toAscii() );
}
}
#-------------------------------------------------
#
# Project created by QtCreator 2011-07-29T19:06:33
#
#-------------------------------------------------
QT += core gui
TARGET = exX
TEMPLATE = app
SOURCES += main.cpp\
filedialogs.cpp
HEADERS += filedialogs.h
This error message is emitted by the MOC compiler. You are missing the Q_OBJECT macro. Put it in your class declaration like this:
class FileDialogs : public QWidget
{
Q_OBJECT
public:
....
I know this Question is very old. But in my case it was another problem.
I had to include the path of the headers manually in the .pro file.
INCLUDEPATH += src/subdir
Related
My child widget does not get keyPressEvents, while if I put the same widget as top level window, it does. I try to set it get focus, but it has no effect on this. Code is below, showing what I try to get to work.
#include <QApplication>
#include <QKeyEvent>
#include <QLCDNumber>
#include <QLabel>
#include <QVBoxLayout>
class DigitSummer: public QLCDNumber {
Q_OBJECT
public:
DigitSummer(QWidget *parent = nullptr) : QLCDNumber(parent) {
}
protected:
void keyPressEvent(QKeyEvent *event) override {
display(intValue() + event->text().toInt());
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
#if 1 // this version does not work, number does not increase
QWidget widget;
widget.setLayout(new QVBoxLayout());
widget.layout()->addWidget(new QLabel("Press digits!"));
DigitSummer summer; // in stack: must be after widget to avoid child delete
widget.layout()->addWidget(&summer);
widget.setFocusProxy(&summer); // I notice no effect!
widget.show();
#else // this version works, number grows with keypresseas
DigitSummer summer;
summer.show();
#endif
return a.exec();
}
#include "main.moc"
And for completenes, .pro file for the same:
QT += core gui widgets
TARGET = QtMCVE
TEMPLATE = app
DEFINES += QT_DEPRECATED_WARNINGS
CONFIG += c++11
QMAKE_CXXFLAGS += -Wall -Wextra
SOURCES += main.cpp
How to fix the widget to receive key events?
This related question suggests installing event filter, but I don't want to do that, there must be a self-contained way to fix the widget itself.
I think you need to set the focus policy for the widget before it will accept keyboard input. In your ctor try...
setFocusPolicy(Qt::StrongFocus);
Having said that, I'm really not sure why the behaviour would differ for top-level and non-top-level widgets.
Working version of the question code:
#include <QApplication>
#include <QKeyEvent>
#include <QLCDNumber>
#include <QLabel>
#include <QVBoxLayout>
class DigitSummer: public QLCDNumber {
Q_OBJECT
public:
DigitSummer(QWidget *parent = nullptr) : QLCDNumber(parent) {
setFocusPolicy(Qt::StrongFocus);
}
protected:
void keyPressEvent(QKeyEvent *event) override {
display(intValue() + event->text().toInt());
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget widget;
widget.setLayout(new QVBoxLayout());
widget.layout()->addWidget(new QLabel("Press digits!"));
widget.layout()->addWidget(new DigitSummer);
widget.show();
return a.exec();
}
#include "main.moc"
This question already has answers here:
When should Q_OBJECT be used?
(4 answers)
QT "No such slot" Error [duplicate]
(1 answer)
Closed 6 years ago.
I have written an UDP programme with Qt, and when I connect this:
connect(socket,SIGNAL(readyRead()),this,SLOT(processPendingDatagrams()));
the complier tells me that
no such slot
the error click here
and I want to know how to fix it, thank you!
P.S.
Here are my files:
files
Here are my codes:
enter code here
udptest.cpp:
#include "udptest.h"
#include <QObject>
#include <QUdpSocket>
#include <QtNetwork>
UDPtest::UDPtest()
{
socket = new QUdpSocket();
port = 2016;
socket->bind(port,QUdpSocket::ShareAddress
| QUdpSocket::ReuseAddressHint);
connect(socket,SIGNAL(readyRead()),this,SLOT(processPendingDatagrams()));
}
QString UDPtest::getIP()
{
QList<QHostAddress> list = QNetworkInterface::allAddresses();
foreach (QHostAddress address, list)
{
if(address.protocol() == QAbstractSocket::IPv4Protocol)
return address.toString();
}
return 0;
}
void UDPtest::sendMessage(QString message)
{
QByteArray data;
QDataStream out(&data,QIODevice::WriteOnly);
QString localHostName = QHostInfo::localHostName();
QString address = getIP();
out <<"123"<< localHostName << address << message;
socket->writeDatagram(data,data.length(),QHostAddress::Broadcast, port);
}
void UDPtest::processPendingDatagrams()
{qDebug()<<"receive";
while(socket->hasPendingDatagrams())
{
QByteArray datagram;
datagram.resize(socket->pendingDatagramSize());
socket->readDatagram(datagram.data(),datagram.size());
QDataStream in(&datagram,QIODevice::ReadOnly);
QString userName,localHostName,ipAddress,message;
QString time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
in >>userName >>localHostName >>ipAddress >>message;
QString msg=time+userName+localHostName+ipAddress+message;
msger=msg;
qDebug()<<msg;
}
}
QString UDPtest:: messager()
{
return msger;
}
main.cpp:
#include"udptest.h"
#include<QDebug>
#include <QtCore/QCoreApplication>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qDebug()<<"123";
UDPtest test;
test.sendMessage("aha");
return a.exec();
}
udptest.h:
#ifndef UDPTEST_H
#define UDPTEST_H
#include <QObject>
#include <QUdpSocket>
#include <QtCore/QCoreApplication>
#include <QtNetwork>
class UDPtest:public QObject
{
public:
UDPtest();
QString messager();
void sendMessage(QString);
private slots:
void processPendingDatagrams();
private:
QString msger;
QUdpSocket *socket;
qint16 port;
QString getIP();
};
#endif // UDPTEST_H
QudptestConsole.pro:
QT += core
QT -= gui
QT += network
CONFIG += c++11
TARGET = QudptestConsole
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp \
udptest.cpp
HEADERS += \
udptest.h
You have forgotten Q_OBJECT macro in UDPtest class
class UDPtest: public QObject
{
Q_OBJECT
public:
UDPtest();
.....
}
I have a simple application in Qt that has a QMainWindow and a QWebEngineView that loads an html page. I've set the QApplication name and the QMainWindow title.
app.setApplicationName("FooApp");
window.setWindowTitle("FooApp Window");
When I use a screen reader, it will read the main window title as:
FooApp C:/Users/tulio/Desktop/TestApp//bin/debug/test.exe
I just need it to read the application name, how can I do this?
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
a.setApplicationName("FooApp");
MainWindow w;
w.setWindowTitle("FooApp Window");
w.show();
return a.exec();
}
mainwindow.cpp
#include "mainwindow.h"
#include <QLayout>
#include <QApplication>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent) {
this->layout()->addWidget(&web_view_);
this->layout()->setMargin(0);
this->resize(QSize(1000, 700));
QString path = QApplication::applicationDirPath() + "/index.html";
qDebug() << QString("HTML Path %1").arg(path);
web_view_.page()->setUrl(QUrl::fromLocalFile(path));
web_view_.resize(this->size());
channel_.registerObject("Test", &test_);
web_view_.page()->setWebChannel(&channel_);
}
MainWindow::~MainWindow() {
}
void MainWindow::resizeEvent(QResizeEvent *event) {
web_view_.resize(event->size());
}
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QWebEngineView>
#include <QResizeEvent>
#include <QWebChannel>
#include <QDebug>
class Test : public QObject
{
Q_OBJECT
public:
explicit Test(QObject *parent=0) : QObject(parent) {}
virtual ~Test() {}
};
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
~MainWindow();
private:
QWebEngineView web_view_;
QWebChannel channel_;
Test test_;
protected:
void resizeEvent(QResizeEvent *event);
};
#endif // MAINWINDOW_H
teste.pro
QT += core gui webengine webenginewidgets webchannel
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = teste
TEMPLATE = app
SOURCES += main.cpp\
mainwindow.cpp
HEADERS += mainwindow.h
index.html
<!DOCTYPE html>
<html>
<body>
<h1>Hello World!</h1>
</body>
</html>
I think you need to use accessibleDescription : QString accessibleName : QString which holds the desciption that gets accessed by assistive technologies.
I tried declaring a signal in a prototype and then connecting it is script funcition for some reason it does not work as I hoped. My code is as follows. Could some one help me in this.
What I expected was, once I called p.setText('New String') in the script code, since setText emits the textChanged signal it should invoke the slot which is catchSignal(text) already connected in the script code.
Prototype header
#ifndef SCRIPTACTION_H
#define SCRIPTACTION_H
#include <QObject>
#include <QtScript>
class ScriptAction : public QObject , public QScriptable
{
Q_OBJECT
public:
ScriptAction(QObject *parent = 0);
signals:
void textChanged(const QString changedString);
};
#endif // SCRIPTACTION_H
Class
#include "scriptaction.h"
#include <QAction>
Q_DECLARE_METATYPE(QAction*)
ScriptAction::ScriptAction(QObject *parent) : QObject(parent)
{
}
Main Class
#include <QApplication>
#include <QDebug>
#include <QAction>
#include "scriptaction.h"
#include <QPushButton>
Q_DECLARE_METATYPE(QAction*)
QScriptValue qAction_Constructor(QScriptContext *ctx, QScriptEngine *eng)
{
qDebug() << "QAction is called";
if(ctx->isCalledAsConstructor())
{
QObject *parent = ctx->argument(0).toQObject();
QAction *action = new QAction("Test",parent);
return eng->newQObject(action, QScriptEngine::ScriptOwnership);
} else {
return QString("invalid call. Use new Constructor");
}
}
int main(int argc, char *argv[])
{
QApplication app(argc,argv);
QScriptEngine engine;
//Evaluating a simaple expresssion
qDebug() << engine.evaluate("1+2").toNumber();
QPushButton button;
QScriptValue buttonScript= engine.newQObject(&button);
engine.globalObject().setProperty("button", buttonScript);
engine.evaluate("button.text ='Hello Text'; button.show()");
//QAction Prototype
ScriptAction qsAction ;
QScriptValue script_proto = engine.newQObject(&qsAction);
engine.setDefaultPrototype(qMetaTypeId<QAction*>(), script_proto);
QScriptValue ctor = engine.newFunction(qAction_Constructor , script_proto);
QScriptValue metaObject = engine.newQMetaObject(&QObject::staticMetaObject, ctor);
engine.globalObject().setProperty("QSAction" , metaObject);
engine.evaluate("var p = new QSAction(button);p.textChanged.connect(catchSignal);");
engine.evaluate("function catchSignal(text) { print ('PROTOTYPE SIGNAL IS CALLED ',text); } p.setText('New String'); " );
return app.exec();
}
I got rid of the issue, and now I see the signal is being triggered and slot is called properly.
All I did was moving the code to a separate script file and start using the QScriptDebugger to see its output. Then I figured there was an error and the code is edited to work.
Anyone who wants an example prototype class, this will hopefully be a good guideline.
#include <QtCore/QCoreApplication>
#include <QTCore>
#include <QtNetwork>
#include <QDebug>
#define CONNECT(sndr, sig, rcvr, slt) connect(sndr, SIGNAL(sig), rcvr, SLOT(slt))
class mynet : QObject
{
Q_OBJECT
public:
mynet()
{}
void start()
{
CONNECT(tcpServer, newConnection(), this, acceptConnection());
CONNECT(tcpClient, connected(), this, startTransfer());
CONNECT(tcpClient, bytesWritten(qint64), this, updateClientProgress(qint64));
CONNECT(tcpClient, error(QAbstractSocket::SocketError), this, displayError(QAbstractSocket::SocketError));
// start server listening
tcpServer->listen();
while(!tcpServer->isListening());
// make client connection
tcpClient->connectToHost(QHostAddress::LocalHost, tcpServer->serverPort());
}
public slots:
void acceptConnection()
{
tcpServerConnection = tcpServer->nextPendingConnection();
CONNECT(tcpServerConnection, readyRead(), this, updateServerProgress());
CONNECT(tcpServerConnection, error(QAbstractSocket::SocketError), this, displayError(QAbstractSocket));
tcpServer->close();
}
void startTransfer()
{
bytesToWrite = TotalBytes - (int)tcpClient->write(QByteArray(PayloadSize, '#'));
}
void updateServerProgress()
{
bytesReceived += (int)tcpServerConnection->bytesAvailable();
tcpServerConnection->readAll();
if (bytesReceived == TotalBytes)
{
qDebug() << "done";
tcpServerConnection->close();
}
}
void updateClientProgress(qint64 numBytes)
{
// callen when the TCP client has written some bytes
bytesWritten += (int)numBytes;
// only write more if not finished and when the Qt write buffer is below a certain size.
if (bytesToWrite > 0 && tcpClient->bytesToWrite() <= 4*PayloadSize)
bytesToWrite -= (int)tcpClient->write(QByteArray(qMin(bytesToWrite, PayloadSize), '#'));
}
void displayError(QAbstractSocket::SocketError socketError)
{
if (socketError == QTcpSocket::RemoteHostClosedError)
return;
qDebug() << tcpClient->errorString();
tcpClient->close();
tcpServer->close();
}
private:
QTcpServer* tcpServer;
QTcpSocket* tcpClient;
QTcpSocket* tcpServerConnection;
int bytesToWrite;
int bytesWritten;
int bytesReceived;
int TotalBytes;
int PayloadSize;
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
mynet m1;
m1.start();
return a.exec();
}
I get an
Undefined symbols for architecture x86_64:
"vtable for mynet", referenced from:
mynet::mynet() in main.o
mynet::~mynet()in main.o.
Please advise what I am doing wrong. Can I not inline the method definitions in the class for some reason in Qt?
You need to add your class to the .pro file
HEADERS += mynet.h
SOURCES += mynet.cpp
so the meta-object compiler can scan them and work out they need moc'ing and generate the relevant stubs.
Assuming that your source file is named foo.cpp, you have to put the following line at the very end:
#include "foo.moc"
This line tells qmake and the VS Qt add-in that the file should be run via moc, and that the generated moc file should be named foo.moc.
You also have problems in the #include lines for Qt headers. I've found that the following work:
#include <QtCore/QCoreApplication>
#include <QtNetwork/QTcpServer>
#include <QtNetwork/QTcpSocket>
Make sure to add network to your .pro file. This will create the correct linking to the network library functions.
QT += core network
Two things:
1) You should publicly derive from QObject.
2) Are you moc'ing this file and then compiling and linking the output? If you include the Q_OBJECT macro and don't moc, you will get an error like that.