Qt中调用控制台并从控制台获取输入

PROBLEN

使用Qt Creator编写代码,打印的输出往往在自带的一个输出窗口中,而这个输出窗口中的输入是无法获取的。如何利用Qt IDE 调出系统的控制台并打印输出到控制台且从控制台获取输入呢?

SOLUTION

1、在pro文件中添加 CONFIG+= console
2、在最左侧选择项目(ctrl + 5)->构建运行 选择运行 将 Run in terminal选中。

这里写图片描述

TEST

MainWindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <iostream>
#include <cstdio>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void on_BtnExp_clicked();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

MainWindow.cpp

#include "MainWindow.h"
#include "ui_MainWindow.h"

using namespace std;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_BtnExp_clicked()
{

    cout<<"this is from cout"<<endl;
    printf("this is from printf \r\n");
    char chIn=getchar();
    cout<<"user input char is "<<chIn<<endl;
}

main.cpp

#include "MainWindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

这里写图片描述

Qt控制台应用程序调用DLL,你可以按照以下步骤进行操作: 1. 将DLL文件放置在Qt项目的文件夹,或者指定其绝对路径。 2. 在Qt项目创建一个头文件(例如,dllwrapper.h),用于声明要调用的DLL函数的函数指针和相关数据结构。 3. 在dllwrapper.h文件,使用`#include`指令包含DLL的头文件。如果DLL没有提供头文件,则需要自己编写函数的声明。 4. 在dllwrapper.h文件,声明函数指针来存储DLL函数的地址。例如,如果要调用名为`MyFunction`的函数,则可以使用以下代码声明函数指针: ```cpp typedef int (*MyFunctionType)(int); ``` 5. 在dllwrapper.h文件,创建一个类或命名空间来管理DLL函数的加载和调用。在类或命名空间,添加一个静态成员函数用于加载DLL并获取函数地址。例如: ```cpp class DLLWrapper { public: static bool loadDLL(); static MyFunctionType myFunction; }; ``` 6. 在dllwrapper.cpp文件实现`loadDLL`和其他函数。`loadDLL`函数,使用`QLibrary`类来加载DLL并获取函数地址。例如: ```cpp bool DLLWrapper::loadDLL() { QLibrary dll("your_dll_name.dll"); if (dll.load()) { myFunction = (MyFunctionType)dll.resolve("MyFunction"); if (myFunction) { return true; } } return false; } ``` 7. 在主函数或其他需要调用DLL函数的地方,调用`loadDLL`函数来加载DLL。例如: ```cpp if (DLLWrapper::loadDLL()) { int result = DLLWrapper::myFunction(42); // 处理DLL函数的返回 } else { // 处理加载DLL失败的情况 } ``` 这样,你就可以在Qt控制台应用程序成功调用DLL函数了。请注意,上述示例代码仅作为演示,你需要根据实际情况进行修改和适配。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值