如何在主窗口中显示文字?

3

我是Qt的新手,我很难找到一个简单的例子来说明如何在主窗口上显示一些文本。例如,我只想将一些文本保存在字符串中,并在主窗口上显示内容。我尝试在mainwindow.cpp中做类似这样的事情,但不成功。

this->setText("Hello, world!\n");
3个回答

7

在您的mainwindow构造函数中执行例如这个

#include <QLabel>
...
QLabel *label = new QLabel(this);
label->setText("first line\nsecond line");

有多种方法可以展示类似的内容,这只是其中一种方式,但它应该能够帮助您开展工作。

以下是一个简单的示例,演示了如何在没有自定义QMainWindow子类的情况下展示:

main.cpp

#include <QLabel>
#include <QMainWindow>
#include <QApplication>

int main(int argc, char **argv)
{
    QApplication application(argc, argv);
    QMainWindow mainWindow;
    QLabel *label = new QLabel(&mainWindow);
    label->setText("first line\nsecond line");
    mainWindow.show();
    return application.exec();
}

main.pro

TEMPLATE = app
TARGET = main
QT += widgets
SOURCES += main.cpp

构建和运行

qmake && make && ./main

1
所有小部件都源自于同一个基类 QWidget,可以通过调用 show() 方法来显示它。
因此,在最基本的层面上,Qt 允许您创建任何小部件并使用最少的代码显示它,甚至不需要显式声明主窗口。
#include <QApplication>
#include <QLabel>

int main(int argc, char **argv)
{
    QApplication app(argc, argv);

    QLabel *label = new QLabel(&mainWindow);
    label->setText("Hello World");
    label->show();

    return app.exec(); // start the main event loop running
}

继续上面的话题,每个小部件都可以提供一个父小部件,使QLabel可以添加到MainWindow(或任何其他小部件)中,如@lpapp所提供的答案所示。

1

您需要在mainWindow中放置一个QLabel,然后执行以下操作:

label->setText("Hello, world!");

然后文本将出现在

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接