[英]C++ - QT - SIGNAL and SLOT understanding
我不明白為什么這段代碼不起作用,也許我還沒有理解SIGNAL和SLOT的概念。
例如:我有一個名為MainWindow
的類,這個類包含ui組件。 在此UI上,我可以啟動和關閉本地服務器。 此服務器在類MyServer
定義。 MainWindow
類引用了MyServer class '&myServer'
。 如果我在類mainwindow.cpp
這樣做,它的工作原理:
connect(ui->startServer,SIGNAL(clicked()),&myServer,SLOT(startServer()));
connect(ui->shutdownServer,SIGNAL(clicked()),&myServer,SLOT(shutDownServer()));
但這一行不是:
connect(&myServer,SIGNAL(signalMessage()), this, SLOT(slotUpdate()));
這個問題是:我有一個名為void signalMessage();
的SIGNAL void signalMessage();
在MyServer類中,此函數在函數void startServer();
調用void startServer();
和void shutDownServer()
signals:
void signalMessage();
通常在MyServer
類中調用singalMessage()
之后,應該調用MainWindow
類中的函數slotUpdate()
。 但是只signalMessage()
而不是slotUpadate()
。
我希望有人理解我的問題。 我可以定義從MainWindow到MyServer的插槽和信號,但不能反向。 :(
編輯: Okey,這里有一些代碼用於理解我的問題:
mainwindow.h
...
public:
Ui::MainWindow *ui;
MyServer myServer;
public slots:
void slotUpdate();
...
mainwindow.cpp
...
connect(ui->startServer,SIGNAL(clicked()),&myServer,SLOT(startServer()));
connect(ui->shutdownServer,SIGNAL(clicked()),&myServer,SLOT(shutDownServer()));
connect(&myServer,SIGNAL(signalMessage()), this, SLOT(slotUpdate()));
...
void MainWindow::slotUpdate()
{
qDebug()<< "update()";
}
...
myserver.h
public slots:
void startServer();//start the server on 127.0.0.1 port: 1234
void shutDownServer();//disconnect threads, shut down server
signals:
void signalMessage();
myserver.cpp
...
void MyServer::startServer(){
if(!this->listen(QHostAddress::Any,1234)){
message.append("Could not start server, because server is already running");
}else{
message.append("Listening...");
}
emit signalMessage();
}
...
void MyServer::signalMessage()
{
qDebug() << "getMessage()";
}
為了接收/發出信號:
故障排除:
CONFIG += console
* .pro文件中的CONFIG += console
)或在運行程序時讀取調試輸出。 如果您輸入錯字並且qt無法連接到信號,它會將有關此問題的消息打印到調試輸出窗口或stdout / stderr中。 這是注意到無法建立連接的唯一方法 - 在運行RUN應用程序(運行時)時建立連接,而不是在編譯時建立連接。 不需要為信號編寫函數體。 如果你必須編寫函數體,那么你的代碼就會出現問題。
也:
Qt有很好的文檔,所以你應該閱讀它如果你安裝了qt,文檔應該通過“助手”程序提供,它也可以在線獲得 。
如果必須定義signalMessage
函數,則意味着您沒有在MyServer
類定義中使用Q_OBJECT
宏。
解決方案:
@arne:
“你在源文件中為函數提供了一個實現,即void MyServer :: signalMessage(){qDebug()<<”getMessage()“;}。這是不正確的。”
“連接語句已經是正確的。你的服務器收到另一個信號的事實表明QOBJECT宏在那里。只需刪除函數實現,即我之前評論中引用的代碼(來自cpp文件)”
所以我必須刪除singalMessage();
的實現singalMessage();
在.cpp文件中。 在此之后連接線(&myServer,SIGNAL(singalMessage()),這,SLOT(slotUpdate())); 作品。
您不能像在myserver.cpp
文件中那樣自己實現signalMessage
。 這樣,來自QObject
那個將被覆蓋,並且不發送信號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.