gpt4 book ai didi

c++ - 从外部类打印到 MainWindow 的元素

转载 作者:行者123 更新时间:2023-11-30 02:53:26 26 4
gpt4 key购买 nike

我已经创建了一组监视外部应用程序的监视程序/帮助程序类,我希望在进行更改时将它们打印到主窗口用户界面内的日志窗口。我的想法是在主线程中创建这个观察器,但我不确定将它链接到我的 MainWindow 的最佳方法。我知道简单地按下面的方式传递它是行不通的,但我不确定这样做的正确方法,如果有的话,因为 Qt 的设计。一些研究表明,将 MainWindow 传递给外部类并不合适,但我不确定是否有更好的方法。

int main(int argc, char *argv[])
{
try {
std::string host = "localhost";
unsigned short port = 8193;
MainWindow w;
w.show();

// Access class for the program that I am watching
UserInterface ui(host, port);
// StatePrinter class, which is registered in the UI and will print changes to MainWindow, ideally
// would I be able to pass something in the StatePrinter constructor to accomplish my goal?
ui.registerObserver(new StatePrinter(w));
UiRunner runner(ui);
boost::thread runnerThread(boost::ref(runner));

w.show();
QApplication a(argc, argv);

runner.cancel();
runnerThread.join();

return a.exec();
} catch(std::exception &ex) {
// ...
}
}

我想有可能在 MainWindow 本身内部创建这个线程,但我更喜欢将它放在 main 中。将我的 StatePrinter 类链接到 MainWindow 的最佳方式是什么?

最佳答案

您可以使您的观察者类本身成为一个 QObject,将其插入一个线程,并在它“注意到”您想要使用日志信息作为信号参数记录的更改时发出信号。

然后,您可以按如下方式将此对象推送到 QThread 中:

QThread* thread = new QThread();
ui->moveToThread(thread);

//Create the needed connections

thread->start();

根据您的需要,您可以将信号连接到线程的 start() 槽,而不是直接调用它。 (阅读 this 了解您的线程需要哪些连接,以便正确启动、停止和清理)。

关于c++ - 从外部类打印到 MainWindow 的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18019286/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com