RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / user-23344

timob256's questions

Martin Hope
timob256
Asked: 2025-01-16 23:16:47 +0000 UTC

esp32无法访问Wi-Fi接口

  • 5

在 esp32 上安装了项目https://github.com/vdeschwb/esp32-signal-generator

一切都已安装,但现在我不知道如何访问网络界面?

我通过Web界面只启动了LED,并且Wi-Fi网络在那里清楚地注册了,但这里我仍然不明白在哪里填写。我只找到了枚举 IPv4 和枚举 IPv6 变量。我不明白如何与它们一起工作,因为它们是空的。

在此输入图像描述

在这个例子中:

// замените своими сетевыми учетными данными
const char* ssid = " Nokia 15";
const char* password = "12345678";

我尝试了地址192.168.4.1(但我无法想象如何在不指定网络的情况下闯入一个难以理解的地址,我立即意识到它不会给出结果。)

esp32
  • 1 个回答
  • 15 Views
Martin Hope
timob256
Asked: 2024-08-22 19:13:09 +0000 UTC

QFileDialog 在 PyQt5 中不起作用

  • 5

QFileDialog在PyQt中不起作用。

主要.py:

from PyQt5 import QtCore, QtGui, QtWidgets, QtMultimedia
import sys


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(634, 312)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.splitter = QtWidgets.QSplitter(self.centralwidget)
        self.splitter.setOrientation(QtCore.Qt.Horizontal)
        self.splitter.setObjectName("splitter")
        self.layoutWidget = QtWidgets.QWidget(self.splitter)
        self.layoutWidget.setObjectName("layoutWidget")
        self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.layoutWidget)
        self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.label = QtWidgets.QLabel(self.layoutWidget)
        self.label.setObjectName("label")
        self.horizontalLayout.addWidget(self.label)
        self.lineEdit = QtWidgets.QLineEdit(self.layoutWidget)
        self.lineEdit.setObjectName("lineEdit")
        self.horizontalLayout.addWidget(self.lineEdit)
        self.pushButton = QtWidgets.QPushButton(self.layoutWidget)
        self.pushButton.setObjectName("pushButton")
        self.pushButton.clicked.connect(self.openFile1) # работает(привязыаем к действию)
        self.pushButton.clicked.connect(self.openFile) # работает(привязыаем к действию)

        self.horizontalLayout.addWidget(self.pushButton)
        self.verticalLayout_2.addLayout(self.horizontalLayout)
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.label_2 = QtWidgets.QLabel(self.layoutWidget)
        self.label_2.setObjectName("label_2")
        self.horizontalLayout_2.addWidget(self.label_2)
        self.lineEdit_2 = QtWidgets.QLineEdit(self.layoutWidget)
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.horizontalLayout_2.addWidget(self.lineEdit_2)
        spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem)
        self.verticalLayout_2.addLayout(self.horizontalLayout_2)
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_3.addItem(spacerItem1)
        self.pushButton_2 = QtWidgets.QPushButton(self.layoutWidget)
        self.pushButton_2.setObjectName("pushButton_2")
        self.horizontalLayout_3.addWidget(self.pushButton_2)
        spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_3.addItem(spacerItem2)
        self.verticalLayout_2.addLayout(self.horizontalLayout_3)
        spacerItem3 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        self.verticalLayout_2.addItem(spacerItem3)
        self.layoutWidget1 = QtWidgets.QWidget(self.splitter)
        self.layoutWidget1.setObjectName("layoutWidget1")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.layoutWidget1)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        self.checkBox_3 = QtWidgets.QCheckBox(self.layoutWidget1)
        self.checkBox_3.setObjectName("checkBox_3")
        self.horizontalLayout_4.addWidget(self.checkBox_3)
        self.label_3 = QtWidgets.QLabel(self.layoutWidget1)
        self.label_3.setObjectName("label_3")
        self.horizontalLayout_4.addWidget(self.label_3)
        spacerItem4 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_4.addItem(spacerItem4)
        self.verticalLayout.addLayout(self.horizontalLayout_4)
        self.horizontalLayout_5 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_5.setObjectName("horizontalLayout_5")
        self.checkBox = QtWidgets.QCheckBox(self.layoutWidget1)
        self.checkBox.setObjectName("checkBox")
        self.horizontalLayout_5.addWidget(self.checkBox)
        spacerItem5 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_5.addItem(spacerItem5)
        spacerItem6 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_5.addItem(spacerItem6)
        self.verticalLayout.addLayout(self.horizontalLayout_5)
        self.textEdit_2 = QtWidgets.QTextEdit(self.layoutWidget1)
        self.textEdit_2.setEnabled(False)
        self.textEdit_2.setObjectName("textEdit_2")
        self.verticalLayout.addWidget(self.textEdit_2)
        self.horizontalLayout_6 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_6.setObjectName("horizontalLayout_6")
        self.checkBox_2 = QtWidgets.QCheckBox(self.layoutWidget1)
        self.checkBox_2.setObjectName("checkBox_2")
        self.horizontalLayout_6.addWidget(self.checkBox_2)
        spacerItem7 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_6.addItem(spacerItem7)
        spacerItem8 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_6.addItem(spacerItem8)
        self.verticalLayout.addLayout(self.horizontalLayout_6)
        self.textEdit = QtWidgets.QTextEdit(self.layoutWidget1)
        self.textEdit.setEnabled(False)
        self.textEdit.setObjectName("textEdit")
        self.verticalLayout.addWidget(self.textEdit)
        self.gridLayout.addWidget(self.splitter, 0, 0, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 634, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label.setText(_translate("MainWindow", "ввдите имя файла"))
        self.pushButton.setText(_translate("MainWindow", "Ввод"))
        self.label_2.setText(_translate("MainWindow", "Кол-во частей"))
        self.pushButton_2.setText(_translate("MainWindow", "Расчёт"))
        self.checkBox_3.setText(_translate("MainWindow", "CheckBox"))
        self.label_3.setText(_translate("MainWindow", "Ввод дополнительных строк "))
        self.checkBox.setText(_translate("MainWindow", "Начало"))
        self.checkBox_2.setText(_translate("MainWindow", "Конец"))
        
    # Для открытия файла используем метод getOpenFileUrl() класса
    # QFileDialog, т. к. для создания экземпляра класса
    # QMediaContent нам нужен путь к файлу, заданный в виде
    # экземпляра класса QUrl
    def openFile(self):
        file = QtWidgets.QFileDialog.getOpenFileUrl(parent=self,
            caption="Выберите звуковой файл",
            filter="Звуковые файлы (*.mp3 *.ac3)")
        
    
    def openFile1(self):
            print("test")


if __name__ == "__main__":

    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

当我按下“Enter”按钮时,出现错误:

runfile('C:/Users/User/Desktop/Kononov/piton/gui.py', wdir='C:/Users/User/Desktop/Kononov/piton') 测试回溯(最近一次调用):

openFile 文件中的文件 c:\users\user\desktop\kononov\piton\gui.py:142 = QtWidgets.QFileDialog.getOpenFileUrl(parent=self,

TypeError:getOpenFileUrl(父:可选[QWidget] = None,标题:可选[str] = '',目录:QUrl = QUrl(),过滤器:可选[str] = '',initialFilter:可选[str] = '' ,选项:Union[QFileDialog.Options,QFileDialog.Option] = 0,supportedSchemes:Iterable[Optional[str]] = []):参数“parent”具有意外类型“Ui_MainWindow”

我无法弄清楚我做错了什么?


感觉好像我错过了一些重要的点,因为我在Qt Designer中创建了视图,然后在pyuic5.exe中运行它

python
  • 2 个回答
  • 14 Views
Martin Hope
timob256
Asked: 2024-02-03 17:59:43 +0000 UTC

找不到 rand 依赖项

  • 5

找不到rand依赖项

Cargo.toml

[package]
name = "guessing_game"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
rand = "0.4.0"

尝试了不同的 rand = "0.4.0" 和 rand = "3.1.4"

写道:

C:\Dima\Rust\guessing_game1>cargo run
    Updating crates.io index
   Compiling winapi v0.3.9
error[E0432]: unresolved import `shared::basetsd`
 --> C:\Users\comp\.cargo\registry\src\index.crates.io-6f17d22bba15001f\winapi-0.3.9\src\shared\minwindef.rs:8:13
  |
8 | use shared::basetsd::{LONG_PTR, UINT_PTR};
  |             ^^^^^^^ could not find `basetsd` in `shared`

error[E0432]: unresolved import `shared::ntdef`
 --> C:\Users\comp\.cargo\registry\src\index.crates.io-6f17d22bba15001f\winapi-0.3.9\src\shared\minwindef.rs:9:13
  |
9 | use shared::ntdef::{HANDLE, LONG};
  |             ^^^^^ could not find `ntdef` in `shared`

error[E0432]: unresolved import `shared::basetsd`
 --> C:\Users\comp\.cargo\registry\src\index.crates.io-6f17d22bba15001f\winapi-0.3.9\src\um\ntsecapi.rs:7:13
  |
7 | use shared::basetsd::{ULONG64, ULONG_PTR};
  |             ^^^^^^^ could not find `basetsd` in `shared`

error[E0432]: unresolved import `shared::ntdef`
  --> C:\Users\comp\.cargo\registry\src\index.crates.io-6f17d22bba15001f\winapi-0.3.9\src\um\ntsecapi.rs:10:13
   |
10 | use shared::ntdef::NTSTATUS;
   |             ^^^^^ could not find `ntdef` in `shared`

error[E0432]: unresolved import `shared::sspi`
  --> C:\Users\comp\.cargo\registry\src\index.crates.io-6f17d22bba15001f\winapi-0.3.9\src\um\ntsecapi.rs:11:13
   |
11 | use shared::sspi::SecHandle;
   |             ^^^^ could not find `sspi` in `shared`

error[E0432]: unresolved import `um::lsalookup`
  --> C:\Users\comp\.cargo\registry\src\index.crates.io-6f17d22bba15001f\winapi-0.3.9\src\um\ntsecapi.rs:12:9
   |
12 | use um::lsalookup::{
   |         ^^^^^^^^^ could not find `lsalookup` in `um`

error[E0432]: unresolved import `um::subauth`
  --> C:\Users\comp\.cargo\registry\src\index.crates.io-6f17d22bba15001f\winapi-0.3.9\src\um\ntsecapi.rs:15:9
   |
15 | use um::subauth::{PUNICODE_STRING, STRING, UNICODE_STRING};
   |         ^^^^^^^ could not find `subauth` in `um`

error[E0432]: unresolved import `shared::basetsd`
 --> C:\Users\comp\.cargo\registry\src\index.crates.io-6f17d22bba15001f\winapi-0.3.9\src\um\winnt.rs:9:13
  |
9 | use shared::basetsd::{
  |             ^^^^^^^ could not find `basetsd` in `shared`

error[E0432]: unresolved import `shared::ktmtypes`
  --> C:\Users\comp\.cargo\registry\src\index.crates.io-6f17d22bba15001f\winapi-0.3.9\src\um\winnt.rs:13:13
   |
13 | use shared::ktmtypes::UOW;
   |             ^^^^^^^^ could not find `ktmtypes` in `shared`

error[E0432]: unresolved import `vc::excpt`
  --> C:\Users\comp\.cargo\registry\src\index.crates.io-6f17d22bba15001f\winapi-0.3.9\src\um\winnt.rs:17:9
   |
17 | use vc::excpt::EXCEPTION_DISPOSITION;
   |         ^^^^^ could not find `excpt` in `vc`

error[E0432]: unresolved import `vc::vcruntime`
  --> C:\Users\comp\.cargo\registry\src\index.crates.io-6f17d22bba15001f\winapi-0.3.9\src\um\winnt.rs:18:9
   |
18 | use vc::vcruntime::size_t;
   |         ^^^^^^^^^ could not find `vcruntime` in `vc`

error[E0432]: unresolved import `shared::ntdef`
   --> C:\Users\comp\.cargo\registry\src\index.crates.io-6f17d22bba15001f\winapi-0.3.9\src\um\winnt.rs:151:17
    |
151 | pub use shared::ntdef::LARGE_INTEGER;
    |                 ^^^^^ could not find `ntdef` in `shared`

error[E0432]: unresolved import `shared::ntdef`
   --> C:\Users\comp\.cargo\registry\src\index.crates.io-6f17d22bba15001f\winapi-0.3.9\src\um\winnt.rs:153:17
    |
153 | pub use shared::ntdef::ULARGE_INTEGER;
    |                 ^^^^^ could not find `ntdef` in `shared`

error[E0432]: unresolved import `shared::ntdef`
   --> C:\Users\comp\.cargo\registry\src\index.crates.io-6f17d22bba15001f\winapi-0.3.9\src\um\winnt.rs:159:17
    |
159 | pub use shared::ntdef::LUID;
    |                 ^^^^^ could not find `ntdef` in `shared`

For more information about this error, try `rustc --explain E0432`.
error: could not compile `winapi` (lib) due to 14 previous errors

C:\Dima\Rust\guessing_game1>

我尝试手动添加兰特

C:\Dima\Rust\guessing_game1>cargo add rand
    Updating crates.io index
      Adding rand v0.4.0 to dependencies.
             Features as of v0.4.1:
             + libc
             + std
             - alloc
             - i128_support
             - nightly

C:\Dima\Rust\guessing_game1>cargo add alloc
    Updating crates.io index
error: the crate `alloc` could not be found in registry index.

C:\Dima\Rust\guessing_game1>cargo add i128_support
    Updating crates.io index
error: the crate `i128_support` could not be found in registry index.

C:\Dima\Rust\guessing_game1>cargo add nightly
    Updating crates.io index
error: the crate `nightly` could not be found in registry index.

C:\Dima\Rust\guessing_game1>cargo add rand
    Updating crates.io index
      Adding rand v0.4.0 to dependencies.
             Features as of v0.4.1:
             + libc
             + std
             - alloc
             - i128_support
             - nightly

但由于某种原因它不支持库。


这是设置

在此输入图像描述

rust
  • 1 个回答
  • 56 Views
Martin Hope
timob256
Asked: 2023-08-15 00:12:25 +0000 UTC

如何创建动态绘图类?

  • 4

开始创建动态图表类并遇到错误,我做错了什么?

标题 QChart 在 kumeik 中连接

#ifndef QDYNAMICCHART_H
#define QDYNAMICCHART_H

#include <QChart>


class QDynamicChart: public QChart
{
    Q_OBJECT
public:
    explicit QDynamicChart(QChart *parent = 0);

    ~QDynamicChart();

    static int ResID;   // Статическая переменная, счетчик номеров графика
    int getID();        // Функция для возврата локального номера графика


public slots:

private:
    int ChartID = 0;   // Локальная переменная, номер графика
};

#endif // QDYNAMICCHART_H

错误

qdynamicchart.h:14:29: Unknown class name 'QChart'; did you mean 'QChar'? (fix available)
:2089:1: note: 'QChar' declared here
change 'QChart' to 'QChar'

qdynamicchart.h:18:28: Unknown type name 'QChart'; did you mean 'QChar'? (fix available)
qchar.h:75:21: 'QChar' declared here
change 'QChart' to 'QChar'
c++
  • 1 个回答
  • 39 Views
Martin Hope
timob256
Asked: 2023-07-30 05:43:48 +0000 UTC

如何清除QCustomPlot中的绘图?

  • 5

我显示了 80 个位置的图表,但是当我打印时,所有 100 个位置都会重新加载。我尝试使用它wGraphic->graph(0)->clearData();但没有成功,而且wGraphic->clearPlottables(); wGraphic->clearGraphs();它通常会导致内存错误。

。H

...
    QCustomPlot *wGraphic;      // Объявляем объект QCustomPlot
   ...
    QVector <double> x; // пока так размеры выставим
    QVector <double> y;

.cpp

    // Инициализируем объект полотна для графика ...
    wGraphic = new QCustomPlot();
    ui->gridLayout->addWidget(wGraphic,2,0,5,5); // ... и устанавливаем
...
 // Добавляем график на полотно
    wGraphic->addGraph(wGraphic->xAxis, wGraphic->yAxis);

    // Подписываем оси координат
    wGraphic->xAxis->setLabel("итерации");
    wGraphic->yAxis->setLabel("Дб");

    // Устанавливаем максимальные и минимальные значения координат
    wGraphic->xAxis->setRange(0,100);
    wGraphic->yAxis->setRange(-50,50);

    // Отрисовываем содержимое полотна
    wGraphic->replot();

    // добавляем красную линию на график
    wGraphic->addGraph(); // red line
    wGraphic->graph(0)->setPen(QPen(QColor(255, 110, 40)));
...
    // тут размеры отрис векторов
    x.reserve(80);
    y.reserve(80);
    // устанавливаем одно значение для всех элементов
    x.fill(0);
    y.fill(0);
...
    x << str_x.toDouble();
    y << str_y.toDouble();

//    qDebug() << "str_priem: " << str_priem;


    qDebug() << "str_x: " << str_x;
    qDebug() << "str_y: " << str_y;

//    wGraphic->graph(0)->clearData();


    wGraphic->graph(0)->setData(y,x);     // Устанавливаем координаты точек графика

//        wGraphic->clearPlottables(); выдаёт ошибку памяти
//    wGraphic->clearGraphs(); выдаёт ошибку памяти

    // Отрисовываем содержимое полотна
    wGraphic->replot();

    //  ???
    wGraphic->update();

    // Очищаем принятую строку
    str_priem.clear();

在此输入图像描述

我希望有这样的东西

在此输入图像描述


我用从链接 https://github.com/eugesh/QCustomPlot下载的文件替换了qcustomplot.cpp这些文件 ,其工作方式与以前的版本相同qcustomplot.h

优点是,现在程序在调用时不会崩溃clear 。

void MainWindow::slotProcessDatagrams()
{
    QByteArray baDatagram_in;
    do {
        baDatagram_in.resize(m_pudp_in->pendingDatagramSize());
        m_pudp_in->readDatagram(baDatagram_in.data(), baDatagram_in.size());
    } while(m_pudp_in->hasPendingDatagrams());

    QDataStream in(&baDatagram_in, QIODevice::ReadOnly);
    in.setVersion(QDataStream::Qt_5_3);

    in >>  str_priem; // принимаем сообщение

    str_x = str_priem.section(' ',0,0);
    str_y = str_priem.section(' ',1);

    x << str_x.toDouble();
    y << str_y.toDouble();

    qDebug() << "str_x: " << str_x;
    qDebug() << "str_y: " << str_y;

    // чистим старое отрисовываем новое
    wGraphic->graph(0)->clear();
    wGraphic->graph(0)->rescaleAxes();

    wGraphic->graph(0)->setData(y,x);     // Устанавливаем координаты точек графика

    // Отрисовываем содержимое полотна
    wGraphic->replot();

    // Очищаем принятую строку
    str_priem.clear();
}

在此输入图像描述

c++
  • 2 个回答
  • 98 Views
Martin Hope
timob256
Asked: 2023-07-28 00:36:01 +0000 UTC

为什么udp无法传输数据?

  • 4

我通过 udipy 发送一条消息,这就是我得到的:

0   1
str_priem:  ""
-9.58924   2
str_priem:  ""
-5.44021   3
str_priem:  ""
6.50288   4
str_priem:  ""
9.12945   5
str_priem:  ""
-1.32352   6
str_priem:  ""
-9.88032   7
str_priem:  ""

这是代码:

事实上,一切都很好,一个发送另一个接收

// тут отправляем сообщение
void MainWindow::onTimeoutStart()
{

    str_ip = ui->lE_enover_id->text();
    str_port = ui->lE_enover_port->text();
    int_port = str_port.toInt(); // превращаем в инты

     // сообщение
    // состоит из двух чисел первое Х второе У
    if(grad >=360 )
    {
        grad = 0;
    }
    data_x = 10 * sin(grad);
    grad = grad + 5;
    if(data_y >= 100)
        data_y = 0;
    data_y = data_y + 1;

    //отправка
    QByteArray baDatagram_out;
    QDataStream out(&baDatagram_out, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_5_3);
    qDebug() << data_x << " " << data_y;
    out << data_x;
    out << data_y;
    if(ui->lE_enover_id->text().isEmpty() == true)
    {
        m_pudp->writeDatagram(baDatagram_out, QHostAddress::LocalHost, int_port);
    }
    else
    {
        m_pudp->writeDatagram(baDatagram_out, QHostAddress(str_ip),  int_port);
    }
}

接受 :

void MainWindow::slotProcessDatagrams()
{
    QByteArray baDatagram_in;
    do {
        baDatagram_in.resize(m_pudp_in->pendingDatagramSize());
        m_pudp_in->readDatagram(baDatagram_in.data(), baDatagram_in.size());
    } while(m_pudp_in->hasPendingDatagrams());

    QDataStream in(&baDatagram_in, QIODevice::ReadOnly);
    in.setVersion(QDataStream::Qt_5_3);
    QString str_priem;
    in >>  str_priem;

    qDebug() << "str_priem: " << str_priem;
    str_priem.clear();
}

在此输入图像描述

qt
  • 1 个回答
  • 27 Views
Martin Hope
timob256
Asked: 2023-07-27 23:14:11 +0000 UTC

QAbstractSocket::UnconnectedState 中未调用 QNativeSocketEngine::bind()

  • 5

我不明白是什么错误,或者更确切地说如何解决它。

启动时运行

void MainWindow::on_pB_start_clicked()
{
    // тут комутирую сигнал, если
    // не по локальной сети и не на мой порт , то
    // конетками не соединяю отправку сигнала и мой график
    // если да то да

    str_ip = ui->lE_enover_id->text();
    str_port = ui->lE_enover_port->text();

    //то отправляем по локальному хосту
    if ( str_ip.isEmpty()  == true )
    {
        int int_port = str_port.toInt(); // превращаем в инты
        m_pudp->bind(QHostAddress::LocalHost, int_port);
    }
    else
    {
        int int_port = str_port.toInt(); // превращаем в инты
        m_pudp->bind(QHostAddress(str_ip), int_port);
    }

    // тут запуск секундомера
    // и при его сробатывании отправляется сообщение  числом в нутри
    timer_start->start(500); // 0.5 секунд

    ui->pB_start->setEnabled(false); // блокируем чтоб заново связ не тянули
}

然后发送消息

// тут отправляем сообщение
void MainWindow::onTimeoutStart()
{

    str_ip = ui->lE_enover_id->text();
    str_port = ui->lE_enover_port->text();
    int_port = str_port.toInt(); // превращаем в инты

     // сообщение
    // состоит из двух чисел первое Х второе У
    if(grad >=360 )
    {
        grad = 0;
    }
    data_x = 10 * sin(grad);
    grad = grad + 5;
    if(data_y >= 100)
        data_y = 0;
    data_y = data_y + 1;

    //отправка
    QByteArray baDatagram_out;
    QDataStream out(&baDatagram_out, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_5_3);
    out << data_x;
    out << data_y;
    if(ui->lE_enover_id->text().isEmpty() == true)
    {
        m_pudp->writeDatagram(baDatagram_out, QHostAddress::LocalHost, int_port);
    }
    else
    {
        m_pudp->writeDatagram(baDatagram_out, QHostAddress(str_ip),  int_port);
    }
}

这是通过单独的套接字进行的接收:

// тут принимаем сообщение ( постоянно в течении 0ю5 сек)
void MainWindow::onTimeoutPlot()
{

    //! если айпишник сменился то закрываем связь и сновоа делаем соединение
    // первичный запуск
    if(ip_me_d == true)
    {
        // сетевые настройки (на приём)
        str_ip_me  =  ui->label_u_ip->text();
        str_port_me = ui->lE_u_port->text();

        int_port_me = str_port_me.toInt(); // превращаем в инты

        //то отправляем по локальному хосту
        if ( str_ip_me.isEmpty()  == true )
        {
             m_pudp_in->bind(QHostAddress::LocalHost, int_port_me);
        }
        else
        {
             m_pudp_in->bind(QHostAddress(str_ip_me), int_port_me);
        }
        // имена для проверки
        str_ip_me_old = str_ip_me;
        str_port_me_old =str_port_me;
        //делаем конект
        connect(m_pudp_in, SIGNAL(readyRead()), SLOT(slotProcessDatagrams()));
        // датчик
        ip_me_d = false;
    }
    // тут сравниваем строку если сторока отличается от строки то биндимся заного на новых правах
    if(ip_me_d == false)
    {
        // проверка на именения
        str_ip_me  =  ui->label_u_ip->text();
        str_port_me = ui->lE_u_port->text();

        // если строки равны, x должен вернуть 0
        int ip_me_verification = QString::compare(str_ip_me, str_ip_me_old, Qt::CaseInsensitive);
        if(ip_me_verification != 0)
        {
            new_m_pudp = true; // айпишник сменился
        }
        int port_me_verification = QString::compare(str_port_me, str_port_me_old, Qt::CaseInsensitive);
        if(port_me_verification != 0)
        {
            new_m_pudp = true; // айпишник сменился
        }
        if(new_m_pudp == true)
        {
            // закрываем старое соединение
            m_pudp_in->close();
            // открываем новое соединение
            // сетевые настройки (на приём)
            str_ip_me  =  ui->label_u_ip->text();
            str_port_me = ui->lE_u_port->text();

            int_port_me = str_port.toInt(); // превращаем в инты

            //то отправляем по локальному хосту
            if ( str_ip_me.isEmpty()  == true )
            {
                 m_pudp_in->bind(QHostAddress::LocalHost, int_port_me);
            }
            else
            {
                 m_pudp_in->bind(QHostAddress(str_ip_me), int_port_me);
            }
            // имена для проверки
            str_ip_me_old = str_ip_me;
            str_port_me_old =str_port_me;
            // датчики настраиваем
            new_m_pudp = false;
  

          ip_me_d = false;
            //делаем конект
            connect(m_pudp_in, SIGNAL(readyRead()), SLOT(slotProcessDatagrams()));

        }
    }
}

void MainWindow::slotProcessDatagrams()
{
    QByteArray baDatagram_in;
    do {
        baDatagram_in.resize(m_pudp_in->pendingDatagramSize());
        m_pudp_in->readDatagram(baDatagram_in.data(), baDatagram_in.size());
    } while(m_pudp_in->hasPendingDatagrams());

    QDataStream in(&baDatagram_in, QIODevice::ReadOnly);
    in.setVersion(QDataStream::Qt_5_3);
    QString str_priem;
    in >>  str_priem;

    qDebug() << "str_priem: " << str_priem;
    str_priem.clear();

}

但为什么会出现错误以及它来自哪里

在此输入图像描述

qt
  • 1 个回答
  • 12 Views
Martin Hope
timob256
Asked: 2023-06-11 03:13:52 +0000 UTC

three.js 库中不显示文字

  • 5

我正在尝试显示文本。这是对附加文本的对象的调用:

  const earthGeometry1 =  new THREE.SphereGeometry( 0, 0, 0 );
            const earthMaterial1=0;
            earth1 = new THREE.Mesh( earthGeometry1, earthMaterial1 );
            scene.add( earth1 );

然后是正文:

const earthDiv1 = document.createElement( 'div' );
            earthDiv1.className = 'label';
            earthDiv1.textContent = 'Earth';
            earthDiv1.style.backgroundColor = 'transparent';

            const earthLabel1 = new CSS2DObject( earthDiv );
            earthLabel1.position.set( 1.5 * EARTH_RADIUS, 0, 0 );
            earthLabel1.center.set( 0, 1 );
            earth1.add( earthLabel1 );
            earthLabel.layers.set( 0 );

            const earthMassDiv1 = document.createElement( 'div' );
            earthMassDiv1.className = 'label';
            earthMassDiv1.textContent = '5.97237e24 kg';
            earthMassDiv1.style.backgroundColor = 'transparent';

            const earthMassLabel1 = new CSS2DObject( earthMassDiv );
            earthMassLabel1.position.set( 1.5 * EARTH_RADIUS, 0, 0 );
            earthMassLabel1.center.set( 0, 0 );
            earth1.add( earthMassLabel1 );
            earthMassLabel1.layers.set( 1 );

但由于某种原因,文本未显示。

这是整个代码:

body{
  overflow: hidden;
  margin: 0;
}
<script async src="https://ga.jspm.io/npm:es-module-shims@1.6.3/dist/es-module-shims.js" crossorigin="anonymous"></script>
<script type="importmap">
  {
    "imports": {
      "three": "https://unpkg.com/three@0.152.0/build/three.module.js",
      "three/addons/": "https://unpkg.com/three@0.152.0/examples/jsm/"
    }
  }
</script>
<script type="module">

import * as THREE from 'three';

        import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

        import Stats from 'three/addons/libs/stats.module.js';

       import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
       
       import { CSS2DRenderer, CSS2DObject } from 'three/addons/renderers/CSS2DRenderer.js';

        let gui;

        let camera, scene, renderer, labelRenderer;

        const layers = {

            'Toggle Name': function () {

                camera.layers.toggle( 0 );

            },
            'Toggle Mass': function () {

                camera.layers.toggle( 1 );

            },
            'Enable All': function () {

                camera.layers.enableAll();

            },

            'Disable All': function () {

                camera.layers.disableAll();

            }

        };
        
        const clock = new THREE.Clock();
        const textureLoader = new THREE.TextureLoader();

        let moon;
        let earth1;

        init();
        animate();

        function init() {

            const EARTH_RADIUS = 1;
            const MOON_RADIUS = 0.27;

            camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.1, 200 );
            camera.position.set( 10, 5, 20 );
            camera.layers.enableAll();

            scene = new THREE.Scene();
            scene.background = new THREE.Color( 0x94afb5 );

            const dirLight = new THREE.DirectionalLight( 0xffffff, 1 );
            dirLight.position.set( 0, 0, 1 );
            dirLight.layers.enableAll();
            scene.add( dirLight );

            //const axesHelper = new THREE.AxesHelper( 5 );
            //axesHelper.layers.enableAll();
            //scene.add( axesHelper );

            //
            const earthGeometry1 =  new THREE.SphereGeometry( 0, 0, 0 );
            const earthMaterial1=0;
            earth1 = new THREE.Mesh( earthGeometry1, earthMaterial1 );
            scene.add( earth1 );
            
            const earthGeometry = new THREE.SphereGeometry( EARTH_RADIUS, 16, 16 );
              const earthMaterial = new THREE.MeshPhongMaterial( {
                specular: 0x333333,
                shininess: 5,
                map: textureLoader.load( 'textures/planets/earth_atmos_2048.jpg' ),
                specularMap: textureLoader.load( 'textures/planets/earth_specular_2048.jpg' ),
                normalMap: textureLoader.load( 'textures/planets/earth_normal_2048.jpg' ),
                normalScale: new THREE.Vector2( 0.85, 0.85 )
            } ); 
            earthMaterial.map.colorSpace = THREE.SRGBColorSpace;
            const earth = new THREE.Mesh( earthGeometry, earthMaterial );
            scene.add( earth );

            const moonGeometry = new THREE.SphereGeometry( MOON_RADIUS, 16, 16 );
            const moonMaterial = new THREE.MeshPhongMaterial( {
                shininess: 5,
                map: textureLoader.load( 'textures/planets/moon_1024.jpg' )
            } );
            moonMaterial.map.colorSpace = THREE.SRGBColorSpace;
            moon = new THREE.Mesh( moonGeometry, moonMaterial );
            scene.add( moon );
            
            //--------------Создаем объект-------------------
const points = [];
points.push(new THREE.Vector3(-10, 10, 0));
points.push(new THREE.Vector3(10, 10, 0));
points.push(new THREE.Vector3(10, -10, 0));
points.push(new THREE.Vector3(-10, -10, 0));
points.push(new THREE.Vector3(-10, 10, 0));
const osxyMaterial = new THREE.LineBasicMaterial({ color: 0x7457bd, linewidth: 1 });
const osxyGeometry = new THREE.BufferGeometry().setFromPoints(points);
const osxy = new THREE.Line(osxyGeometry, osxyMaterial);
scene.add(osxy);

const points1 = [];
points1.push(new THREE.Vector3(0, -10, 10));//Указываем вектор первой точки
points1.push(new THREE.Vector3(0, 10, 10));//Указываем вектор второй точки
points1.push(new THREE.Vector3(0, 10, -10));
points1.push(new THREE.Vector3(0, -10, -10));
points1.push(new THREE.Vector3(0, -10, 10));
const osxzMaterial = new THREE.LineBasicMaterial({ color: 0x3d803d, linewidth: 1 });
const osxzGeometry = new THREE.BufferGeometry().setFromPoints(points1);
const osxz = new THREE.Line(osxzGeometry, osxzMaterial);
scene.add(osxz);

const points2 = []
points2.push(new THREE.Vector3(-10, 0, 10));//Указываем вектор первой точки
points2.push(new THREE.Vector3(10, 0, 10));//Указываем вектор второй точки
points2.push(new THREE.Vector3(10, 0, -10));
points2.push(new THREE.Vector3(-10, 0, -10));
points2.push(new THREE.Vector3(-10, 0, 10));
const osyzMaterial = new THREE.LineBasicMaterial({ color: 0xab5641, linewidth: 1 })
const osyzGeometry = new THREE.BufferGeometry().setFromPoints(points2)
const osyz = new THREE.Line(osyzGeometry, osyzMaterial)
scene.add(osyz) 

            //

            earth.layers.enableAll();
            moon.layers.enableAll();

            const earthDiv = document.createElement( 'div' );
            earthDiv.className = 'label';
            earthDiv.textContent = 'Earth';
            earthDiv.style.backgroundColor = 'transparent';

            const earthLabel = new CSS2DObject( earthDiv );
            earthLabel.position.set( 1.5 * EARTH_RADIUS, 0, 0 );
            earthLabel.center.set( 0, 1 );
            earth.add( earthLabel );
            earthLabel.layers.set( 0 );

            const earthMassDiv = document.createElement( 'div' );
            earthMassDiv.className = 'label';
            earthMassDiv.textContent = '5.97237e24 kg';
            earthMassDiv.style.backgroundColor = 'transparent';

            const earthMassLabel = new CSS2DObject( earthMassDiv );
            earthMassLabel.position.set( 1.5 * EARTH_RADIUS, 0, 0 );
            earthMassLabel.center.set( 0, 0 );
            earth.add( earthMassLabel );
            earthMassLabel.layers.set( 1 );
            
            //-
            const earthDiv1 = document.createElement( 'div' );
            earthDiv1.className = 'label';
            earthDiv1.textContent = 'Earth';
            earthDiv1.style.backgroundColor = 'transparent';

            const earthLabel1 = new CSS2DObject( earthDiv );
            earthLabel1.position.set( 1.5 * EARTH_RADIUS, 0, 0 );
            earthLabel1.center.set( 0, 1 );
            earth1.add( earthLabel1 );
            earthLabel.layers.set( 0 );

            const earthMassDiv1 = document.createElement( 'div' );
            earthMassDiv1.className = 'label';
            earthMassDiv1.textContent = '5.97237e24 kg';
            earthMassDiv1.style.backgroundColor = 'transparent';

            const earthMassLabel1 = new CSS2DObject( earthMassDiv );
            earthMassLabel1.position.set( 1.5 * EARTH_RADIUS, 0, 0 );
            earthMassLabel1.center.set( 0, 0 );
            earth1.add( earthMassLabel1 );
            earthMassLabel1.layers.set( 1 );
//-

            const moonDiv = document.createElement( 'div' );
            moonDiv.className = 'label';
            moonDiv.textContent = 'Moon';
            moonDiv.style.backgroundColor = 'transparent';

            const moonLabel = new CSS2DObject( moonDiv );
            moonLabel.position.set( 1.5 * MOON_RADIUS, 0, 0 );
            moonLabel.center.set( 0, 1 );
            moon.add( moonLabel );
            moonLabel.layers.set( 0 );

            const moonMassDiv = document.createElement( 'div' );
            moonMassDiv.className = 'label';
            moonMassDiv.textContent = '7.342e22 kg';
            moonMassDiv.style.backgroundColor = 'transparent';

            const moonMassLabel = new CSS2DObject( moonMassDiv );
            moonMassLabel.position.set( 1.5 * MOON_RADIUS, 0, 0 );
            moonMassLabel.center.set( 0, 0 );
            moon.add( moonMassLabel );
            moonMassLabel.layers.set( 1 );

            //
            renderer = new THREE.WebGLRenderer();
            renderer.setPixelRatio( window.devicePixelRatio );
            renderer.setSize( window.innerWidth, window.innerHeight );
            document.body.appendChild( renderer.domElement );

            labelRenderer = new CSS2DRenderer();
            labelRenderer.setSize( window.innerWidth, window.innerHeight );
            labelRenderer.domElement.style.position = 'absolute';
            labelRenderer.domElement.style.top = '0px';
            document.body.appendChild( labelRenderer.domElement );

            const controls = new OrbitControls( camera, labelRenderer.domElement );
            controls.minDistance = 5;
            controls.maxDistance = 100;

            //

            window.addEventListener( 'resize', onWindowResize );

            initGui();

        }

        function onWindowResize() {

            camera.aspect = window.innerWidth / window.innerHeight;

            camera.updateProjectionMatrix();

            renderer.setSize( window.innerWidth, window.innerHeight );

            labelRenderer.setSize( window.innerWidth, window.innerHeight );

        }


        function animate() {

            requestAnimationFrame( animate );

            const elapsed = clock.getElapsedTime();

            moon.position.set( Math.sin( elapsed ) * 5, 0, Math.cos( elapsed ) * 5 );

            renderer.render( scene, camera );
            labelRenderer.render( scene, camera );

        }

        //

        function initGui() {

            gui = new GUI();

            gui.title( 'Camera Layers' );

            gui.add( layers, 'Toggle Name' );
            gui.add( layers, 'Toggle Mass' );
            gui.add( layers, 'Enable All' );
            gui.add( layers, 'Disable All' );

            gui.open();

        }

    </script>

gui
  • 1 个回答
  • 16 Views
Martin Hope
timob256
Asked: 2022-08-29 23:05:34 +0000 UTC

如何在 Qt 中重绘按钮?

  • -2

我想显示一个按钮,它具有按钮的标准功能(QPushButton),但同时具有不同的外观

但是由于某种原因,他们不允许推断从 QPushButton 继承的类

在此处输入图像描述

这是代码(我无法弄清楚我做错了什么):

CMakeLists.txt

cmake_minimum_required(VERSION 3.5)

project(myButton VERSION 0.1 LANGUAGES CXX)

set(CMAKE_INCLUDE_CURRENT_DIR ON)

set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

find_package(QT NAMES Qt6 Qt5 COMPONENTS Widgets REQUIRED)
find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Widgets REQUIRED)

set(PROJECT_SOURCES
        main.cpp
        mainwindow.cpp
        mainwindow.h
        mainwindow.ui
        custombutton.cpp
        custombutton.h
        lineitem.cpp
        lineitem.h
)

if(${QT_VERSION_MAJOR} GREATER_EQUAL 6)
    qt_add_executable(myButton
        MANUAL_FINALIZATION
        ${PROJECT_SOURCES}
    )
# Define target properties for Android with Qt 6 as:
#    set_property(TARGET myButton APPEND PROPERTY QT_ANDROID_PACKAGE_SOURCE_DIR
#                 ${CMAKE_CURRENT_SOURCE_DIR}/android)
# For more information, see https://doc.qt.io/qt-6/qt-add-executable.html#target-creation
else()
    if(ANDROID)
        add_library(myButton SHARED
            ${PROJECT_SOURCES}
        )
# Define properties for Android with Qt 5 after find_package() calls as:
#    set(ANDROID_PACKAGE_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/android")
    else()
        add_executable(myButton
            ${PROJECT_SOURCES}
        )
    endif()
endif()

target_link_libraries(myButton PRIVATE Qt${QT_VERSION_MAJOR}::Widgets)

set_target_properties(myButton PROPERTIES
    MACOSX_BUNDLE_GUI_IDENTIFIER my.example.com
    MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION}
    MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}
)

if(QT_VERSION_MAJOR EQUAL 6)
    qt_finalize_executable(myButton)
endif()

主文件

#include "mainwindow.h"

#include <QApplication>

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

主窗口.cpp

#include "mainwindow.h"
#include "./ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)

{
    _line = new lineItem(this);

    ui->setupUi(this);

    ui->gridLayout->addItem(_line);
}

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

主窗口.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

#include "lineitem.h"


QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private:
    Ui::MainWindow *ui;

    lineItem*  _line;

};
#endif // MAINWINDOW_H

    

自定义按钮.cpp

#include "custombutton.h"

customButton::customButton(QPushButton *parent)
    : QPushButton{parent}
{
    _myPushButton = qobject_cast<QPushButton*>(parent);
}

void customButton::setPosition(float radiusPos, float angle)
{

    if(radiusPos<0)
        _rPos = 0;
    else
        _rPos = radiusPos;

    if(angle>360)
        _angle = 360;
    else if(radiusPos<0)
        _angle = 0;
    else
        _angle = angle;

    _myPushButton->update();
}

QPointF customButton::getCenterPoint(float radPos, float angle)
{
    float r = getRadius(_myPushButton->rect());
    float xx=cos(qDegreesToRadians(angle+90))*r;
    float yy=sin(qDegreesToRadians(angle+90))*r;

    QPointF pt;
    xx=_myPushButton->rect().center().x()-xx*radPos;
    yy=_myPushButton->rect().center().y()-yy*radPos;
    pt.setX(xx);
    pt.setY(yy);
    return pt;
}


void customButton::setColors(const QColor &substrate, const QColor &item, const QColor &outline)
{
    _colorSubstrate = substrate;
    _colorItem = item;
    _colorOutline = outline;
}

void customButton::setValueRange(float minValue, float maxValue)
{
    _minValue = minValue;
    _maxValue = maxValue;
}

void customButton::setDegreeRange(float minDegree, float maxDegree)
{
    _minDegree = minDegree;
    _maxDegree = maxDegree;
}

void customButton::setSubstrate(bool val)
{
    _drawSubstrate = val;
}

void customButton::setThicknessOutline(float val)
{
    _thicknessOutline = val;
}

void customButton::setOutline(bool val)
{
    _drawOutline = val;
}

void customButton::setShadow(bool val)
{
    _drawShadow = val;
}

float customButton::getRadius(const QRectF &tmpRect)
{
    float r = 0;
    if(tmpRect.width() < tmpRect.height()*_wh)
        r = tmpRect.width()/(2.0*_wh);
    else
        r = tmpRect.height()/2.0;
    return r;
}

float customButton::getDegFromValue(float val)
{
    float a = (_maxDegree-_minDegree)/(_maxValue-_minValue);
    float b = -a*_minValue+_minDegree;
    return a*val+b;
}

void customButton::setScaleFactor(float val)
{
    _scaleFactor = val;
}

void customButton::setThickness(float val)
{
    _thickness = val;
}

void customButton::setProportions(float wh)
{
    _wh = wh;
}
    

自定义按钮.h

#ifndef BUTTONITEM_H
#define BUTTONITEM_H

#include <QObject>
#include <QButtonGroup>
#include <QPushButton>

#include <QPainter>
#include <QColor>
#include <QFont>
#include <QDebug>

#include <QPainterPath>
#include <QPointF>
#include <QRect>
#include <QGraphicsBlurEffect>
#include <QGraphicsItem>
#include <QtMath>
#include <QMessageBox>

class customButton : public QPushButton
{

public:
    explicit customButton(QPushButton *parent = nullptr);

    virtual void draw(QPainter *p) = 0;

    ///
    /// \brief setPosition установить радиус (1=100%) и угол (в градусах) определяющий расположение item на виджете
    ///
    void setPosition(float radiusPos , float angle);

    ///
    /// \brief getPoint расчитать центральную точку
    ///
    QPointF getCenterPoint(float radPos, float angle);

    ///
    /// \brief setColors: установить три цвета ( подложки, основной и обводки) для item
    ///
    void setColors(const QColor &substrate, const QColor &item, const QColor &outline);

    ///
    /// \brief setValueRange установить диапазон изменения значения
    ///
    void setValueRange(float minValue,float maxValue);

    ///
    /// \brief setDegreeRange установить диапазон изменения угла
    ///
    void setDegreeRange(float minDegree,float maxDegree);

    /// inner function

    ///
    /// \brief включить отрисовку подложки с заданным ранее цветом и прозрачностью
    ///
    void setSubstrate(bool val);

    ///
    /// \brief setThicknessOutline установить толщину обводки
    ///
    void setThicknessOutline(float val);

    ///
    /// \brief включить отрисовку подложки с заданным ранее цветом и прозрачностью
    ///
    void setOutline(bool val);

    ///
    /// \brief включить отрисовку "тени"
    ///
    void setShadow(bool val);

    ///
    /// \brief getRadius получить радиус окружности в которую вписан заданный прямоугольник
    ///
    float getRadius(const QRectF &tmpRect);

    ///
    /// \brief getDegFromValue
    ///
    float getDegFromValue(float val);

    ///
    /// \brief setScaleFactor установить коэффициент масштаба
    ///
    void setScaleFactor(float val);

    ///
    /// \brief setThickness установить толщину линии
    ///
    void setThickness(float val);

    ///
    /// \brief setProportions задать соотношение ширины к высоте в виджете с данным item
    ///
    void setProportions(float wh);

//    QWidget *_parentWidget;
    QPushButton *_myPushButton;


    QColor   _colorSubstrate    {Qt::black};
    QColor   _colorItem         {Qt::black};
    QColor   _colorOutline      {Qt::white};
    QColor   _colorCornerBound  {Qt::darkRed};

    QColor   _colorShadowB      {Qt::black};
    QColor   _colorShadowW      {Qt::white};

    QColor   _colorKaracurtWhite  {255, 255, 255, 255};
    QColor   _colorKaracurtYellow {255, 255,  0 , 255};
    QColor   _colorKaracurtSubstrate { 0, 0,  0 , 128};
    QColor   _colorKaracurtShadow { 0 ,  0 ,  0 , 200};


    float    _thicknessOutline  {5};
    float    _thickness         {3};

    float    _scaleFactor       {1};

    float    _rPos              {0.5};
    float    _angle             {0.5};

    float    _minValue          {0};
    float    _maxValue          {100};
    float    _minDegree         {0};
    float    _maxDegree         {360};

    bool     _drawSubstrate     {false};
    bool     _drawOutline       {false};
    bool     _drawShadow        {false};

    float    _wh                {1};


signals:

};

#endif // BUTTONITEM_H

    

lineitem.cpp

#include "lineitem.h"

lineItem::lineItem(QPushButton *parent)
    : customButton(parent)
{

}

void lineItem::draw(QPainter *p)
{
    p->save();

    QPointF center = getCenterPoint(_rPos, _angle);
    float r = getRadius(_myPushButton->rect())*_scaleFactor;

    if(_drawSubstrate)
    {
        p->setBrush(QBrush(_colorSubstrate));
        p->drawEllipse(center,(int)(r), (int)(r));
    }

    p->translate(center);

    p->setPen(Qt::NoPen);
    p->setBrush(QBrush(_color));
    p->drawRect(-r/1.5, -r/1.5, r*1.34, r*1.34);


    QVector<QPointF> tmpPoints;
    tmpPoints.append(QPointF(0.0 - r*0.46 , 0.0 + r*0.2 ));
    tmpPoints.append(QPointF(0.0 - r*0.36 , 0.0 + r*0.2 ));

    tmpPoints.append(QPointF(0.0 - r*0.26 , 0.0 - r*0.15 ));
    tmpPoints.append(QPointF(0.0 - r*0.06 , 0.0 + r*0.45 ));

    tmpPoints.append(QPointF(0.0 + r*0.06 , 0.0 - r*0.4  ));
    tmpPoints.append(QPointF(0.0 + r*0.26 , 0.0 + r*0.25 ));

    tmpPoints.append(QPointF(0.0 + r*0.36 , 0.0 + r*0.1 ));
    tmpPoints.append(QPointF(0.0 + r*0.46 , 0.0 + r*0.1 ));

    QPainterPath path;
    path.addPolygon(tmpPoints);

    p->setBrush(Qt::NoBrush);
    p->setPen(QPen(_color_line, 2*_thickness, Qt::SolidLine));
    p->drawPath(path);

    p->restore();
}
    

lineitem.h

#ifndef LINEITEM_H
#define LINEITEM_H

#include "custombutton.h"

class lineItem : public customButton
{
public:
    lineItem();

    explicit lineItem(QPushButton *parent = nullptr);

    virtual void draw(QPainter * p) override final;

    private:

        QColor   _color        {220, 0, 0, 227};
        QColor   _color_line {255,255,255,255};
};
#endif // LINEITEM_H
qt
  • 1 个回答
  • 33 Views
Martin Hope
timob256
Asked: 2022-09-04 12:58:09 +0000 UTC

如何把一个数字写五遍

  • -4
// выставляем точку отчёта
float a_t_pitch = _direction;        // точка отрисовки

a_t_pitch = a_t_pitch - 80.0;        // отклад 80 градусов
if(a_t_pitch < 0)
    a_t_pitch = a_t_pitch + 360.0;

qDebug() << a_t_pitch;

 float a = 0;
 for(;a<=160.0;a= a+0.1)
 {
     if (a_t_pitch >= 360.0){
         a_t_pitch = a_t_pitch - 360.0;  }
     if (a_t_pitch <= -0.1)
         a_t_pitch = a_t_pitch + 360.0;

     if(((int)a_t_pitch % (int)30.0) == 0)
     {
          qDebug() << "позиция " << a_t_pitch;
     }
     a_t_pitch= a_t_pitch +0.1;
 }

这就是它给我的:

280 
позиция  300.001
позиция  300.101
позиция  300.201
позиция  300.301
позиция  300.401
позиция  300.501
позиция  300.601
позиция  300.701
позиция  300.801
позиция  300.901
позиция  330.003
позиция  330.103
позиция  330.203
позиция  330.303
позиция  330.403
позиция  330.503
позиция  330.603
позиция  330.703
позиция  330.803
позиция  330.903
позиция  0.00488281
позиция  0.104883
позиция  0.204883
позиция  0.304883
позиция  0.404883
позиция  0.504883
позиция  0.604883
позиция  0.704883
позиция  0.804883
позиция  0.904883
позиция  30.005
позиция  30.105
позиция  30.205
позиция  30.305
позиция  30.405
позиция  30.505
позиция  30.605
позиция  30.705
позиция  30.805
позиция  30.905
позиция  60.0045
позиция  60.1045
позиция  60.2045
позиция  60.3045
позиция  60.4045
позиция  60.5045
позиция  60.6045
позиция  60.7045
позиция  60.8045
позиция  60.9045

如何修复这个逻辑(最好是这一行if(((int)a_t_pitch % (int)30.0) == 0)),使其不接受像 0.00488281 这样的值

其实有必要拿出来,五次

позиция  300
позиция  330
позиция  0
позиция  30
позиция  60
c++
  • 1 个回答
  • 10 Views
Martin Hope
timob256
Asked: 2022-08-10 18:49:06 +0000 UTC

QPainterPath 中 QPainter 旋转的类比是什么?

  • -1

QPainter rotate我在 QPainterPath 类中找不到类似物

if(_myTexpr.outline == true)
        {
            path2.translate(_myTexpr.screen_size_x/2.0, _myTexpr.screen_size_y/2.0);
            path2.rotate(); // вот тут выдаёт ошибку 
            path2.translate(-_myTexpr.screen_size_x/2.0, -_myTexpr.screen_size_y/2.0);
            
        }
        painter.translate(this->width()/2.0, this->height()/2.0);
        painter.rotate(_myTexpr.m_pitch);
        painter.translate(- this->width()/2.0, - this->height()/2.0);
qt
  • 1 个回答
  • 10 Views
Martin Hope
timob256
Asked: 2022-08-09 05:54:55 +0000 UTC

如何用 QColor 替换数组?

  • -1

我正在尝试int rgb[4]; // цвет в конце тонеля用QColor rgb;

从课堂上打电话wgt_screen.cpp

 //   фон  работает
if(_myTexpr.substrate == true)
{
    painter.setBrush(QColor(_myTexpr.rgb[0], _myTexpr.rgb[1], _myTexpr.rgb[2], _myTexpr.rgb[3]));   
    painter.drawRect( 0, 0, _myTexpr.screen_size_x, _myTexpr.screen_size_y);                         // рисуем квадрат

}
if(_myTexpr.substrate == false)
{
    painter.setBrush(QColor(250,250,250,250));      
    painter.drawRect( 0, 0, _myTexpr.screen_size_x, _myTexpr.screen_size_y);
}

这是他的seters和heter

bool wgt_screen::get_substrate()
{
    return _myTexpr.substrate;
}

void wgt_screen::set_substrate(bool val, int rgb0, int rgb1, int rgb2, int rgb3 )
{

    _myTexpr.substrate = val;

    _myTexpr. rgb[0] = rgb0;_myTexpr. rgb[1] = rgb1;
    _myTexpr. rgb[2] = rgb2;_myTexpr. rgb[3] = rgb3;
    update();
}

从课堂上打电话mainwindows.cpp

void mainwindow::keyPressEvent(QKeyEvent *event)
{
    switch (event->key()) {
    case Qt::Key_A: // фон
        if(wgt->get_substrate())
        {
             // wgt -wgt_screen.cpp
             wgt->set_substrate(false, 48, 172, 220, 120);
        }
        else
        {
            wgt->set_substrate(true, 48, 172, 220, 120);
        }
        break;
...

当我用 QColor 替换数组时,它停止工作:(
QColor rgb;

    // ---------рисуем фон ------------
    if(_myTexpr.substrate == true)
    {
     //  bgfon.setColor(Qt::red);
        bgfon.setColor(_myTexpr.rgb);
        painter.setBrush(bgfon);
        painter.drawRect( 0, 0, _myTexpr.screen_size_x, _myTexpr.screen_size_y);                         // рисуем квадрат

    }
    if(_myTexpr.substrate == false)
    {
        bgfon.setColor(QColor(250,250,250,250));
        painter.setBrush(bgfon);
        painter.drawRect( 0, 0, _myTexpr.screen_size_x, _myTexpr.screen_size_y);
    }

这是setter和getter

bool  wgt_screen::get_substrate()
{
    return _myTexpr.substrate;
}

void  wgt_screen::set_substrate(bool val, QColor me_rgb)
{
    _myTexpr.substrate = val;
    _myTexpr.rgb = me_rgb;
     update();
}

这是一个挑战

void mainwindow::keyPressEvent(QKeyEvent *event)
{
    switch (event->key()) {
     case Qt::Key_A: // фон
        if(wgt->get_substrate())
        {
            qDebug() << "set_fonn true ";
            QColor  rgb;
            rgb.setRgbF(1.0, 0.2, 0.6, 1.0);
            wgt->set_substrate(false, rgb);
        }
        else
        {
           QColor  rgb;
           rgb.setRgbF(1.0, 0.2, 0.6, 1.0);
            wgt->set_substrate(true, rgb);
        }
        break;

不幸的是,由于某种原因它不起作用:(

qt 只是不写错误,按下“A”按钮时没有任何反应,背景不会改变颜色,而按钮本身可以工作。

qt
  • 1 个回答
  • 10 Views
Martin Hope
timob256
Asked: 2022-07-12 04:50:10 +0000 UTC

如何找到一条线的长度(以像素为单位)?

  • -1

我曾经以这种方式找出字符串的长度(在 Kut 5.12 中工作)

QFont razm_shrift("Areal", _myTexpr.m_t_razm[7]*2.4, QFont::Light);         // свойства шрифта
painter.setFont(razm_shrift);                                               // устанавливаем размер шрифта
QFontMetrics stroka_razm = painter.fontMetrics();                           // метрика шрифта

_myTexpr.nadp1 = "Строка"
  
_myTexpr.m_t_razm[8] = stroka_razm.width(_myTexpr.nadp1);               // узнаём ширину строки

现在我做不到 f_zh (kute 6.2)

在此处输入图像描述

现在怎么办???0_o

qt
  • 1 个回答
  • 10 Views
Martin Hope
timob256
Asked: 2022-06-24 16:32:57 +0000 UTC

如何更改布尔变量的值

  • -2

就像我在拉丁语中按下按钮 A

case Qt::Key_A:
    if(_myTexpr.substrate == true || _myTexpr.substrate == false)
        setSubstrate(true);
    else
        setSubstrate(false);

由于某种原因不会将 false 更改为 true

c++
  • 3 个回答
  • 10 Views
Martin Hope
timob256
Asked: 2022-05-21 21:26:50 +0000 UTC

错误:SDL/SDL_gamecontroller.h:没有这样的文件或目录#include <SDL/SDL_gamecontroller.h>

  • -1

收集到 Urho3D-1.8-ALPHA(一切都组装好了)

决定从Urho3D构建一个简单的示例

但由于某种原因,它写入的文件甚至不在项目中(受保护的内部),没有标题 SDL_gamecontroller.h ,虽然它不存在这样的文件在 SDL2/SDL_gamecontroller.h 但我不想修复内部系统文件

我无法理解他(cmake)是如何收集所有示例的,但我无法应付(我连接了所有库),这是本地化错误:

urno_example1.pro

#-------------------------------------------------
#
# Project created by QtCreator 2021-12-21T11:52:47
#
#-------------------------------------------------

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = urno_example1
TEMPLATE = app

# The following define makes your compiler emit warnings if you use
# any feature of Qt which has been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0


SOURCES += \
#        main.cpp \
#        mainwindow.cpp
    HelloWorld.cpp \
    Sample.inl

HEADERS += \
#        mainwindow.h
    HelloWorld.h \
    Sample.h

INCLUDEPATH +=/home/dima/ogre/Urho3D-1.8-ALPHA/Source/ThirdParty/SDL/include \
        /home/dima/ogre/Urho3D-1.8-ALPHA/build/Source/ThirdParty/SDL/include/generated \
        /usr/local/include/Urho3D                                             \
#    /home/dima/ogre/Urho3D-1.8-ALPHA/build/include/Urho3D                    \
#    /home/dima/ogre/Urho3D-1.8-ALPHA/build/include/Urho3D/ThirdParty/SDL     \
#    /usr/include/SDL                                                         \
#    /usr/include/SDL2


unix:!macx: LIBS += -L$$PWD/../../../../usr/local/lib/Urho3D/ -lUrho3D

INCLUDEPATH += $$PWD/../../ogre/Urho3D-1.8-ALPHA/Source/Urho3D
DEPENDPATH += $$PWD/../../ogre/Urho3D-1.8-ALPHA/Source/Urho3D

unix:!macx: PRE_TARGETDEPS += $$PWD/../../../../usr/local/lib/Urho3D/libUrho3D.a

unix:!macx: LIBS += -L$$PWD/../../ogre/Urho3D-1.8-ALPHA/build/Source/ThirdParty/SDL/ -lSDL

INCLUDEPATH += $$PWD/../../ogre/Urho3D-1.8-ALPHA/Source/ThirdParty/SDL/include
DEPENDPATH += $$PWD/../../ogre/Urho3D-1.8-ALPHA/Source/ThirdParty/SDL/include

unix:!macx: PRE_TARGETDEPS += $$PWD/../../ogre/Urho3D-1.8-ALPHA/build/Source/ThirdParty/SDL/libSDL.a


# --- linux ---

unix:!macx: LIBS += -L$$PWD/../../../../usr/lib/x86_64-linux-gnu/ -lOpenGL

INCLUDEPATH += $$PWD/../../../../usr/include/GL
DEPENDPATH += $$PWD/../../../../usr/include/GL

unix:!macx: LIBS += -L$$PWD/../../../../usr/lib/x86_64-linux-gnu/ -lGLEW

INCLUDEPATH += $$PWD/../../../../usr/include/GL
DEPENDPATH += $$PWD/../../../../usr/include/GL

unix:!macx: LIBS += -L$$PWD/../../../../usr/lib/x86_64-linux-gnu/ -lglut

INCLUDEPATH += $$PWD/../../../../usr/include/GL
DEPENDPATH += $$PWD/../../../../usr/include/GL

unix:!macx: LIBS += -L$$PWD/../../../../usr/lib/x86_64-linux-gnu/ -lGLU

INCLUDEPATH += $$PWD/../../../../usr/include/GL
DEPENDPATH += $$PWD/../../../../usr/include/GL


//
// Copyright (c) 2008-2019 the Urho3D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

你好世界.h

    #pragma once
    #include "SDL.h"
    #include "Sample.h"
    
    /// This first example, maintaining tradition, prints a "Hello World" message.
    /// Furthermore it shows:
    ///     - Using the Sample / Application classes, which initialize the Urho3D engine and run the main loop
    ///     - Adding a Text element to the graphical user interface
    ///     - Subscribing to and handling of update events
    class HelloWorld : public Sample
    {
        URHO3D_OBJECT(HelloWorld, Sample);
    
    public:
        /// Construct.
        explicit HelloWorld(Context* context);
    
        /// Setup after engine initialization and before running the main loop.
        void Start() override;
    
    protected:
        /// Return XML patch instructions for screen joystick layout for a specific sample app, if any.
        String GetScreenJoystickPatchString() const override { return
            "<patch>"
            "    <add sel=\"/element/element[./attribute[@name='Name' and @value='Hat0']]\">"
            "        <attribute name=\"Is Visible\" value=\"false\" />"
            "    </add>"
            "</patch>";
        }
    
    private:
        /// Construct a new Text instance, containing the 'Hello World' String, and add it to the UI root element.
        void CreateText();
        /// Subscribe to application-wide logic update events.
        void SubscribeToEvents();
        /// Handle the logic update event.
        void HandleUpdate(StringHash eventType, VariantMap& eventData);
    };

/usr/local/include/Urho3D/Input/InputConstants.h:31: ошибка: SDL/SDL_gamecontroller.h: No such file or directory
 #include <SDL/SDL_gamecontroller.h>
                                    ^

жалуется на /usr/local/include/Urho3D/Input/InputConstants.h 

我将如何跳过这个挑剔的 vseravno 控制器将无法连接。


在此处输入图像描述

在此处输入图像描述

qtcreator
  • 1 个回答
  • 10 Views
Martin Hope
timob256
Asked: 2022-05-06 22:56:17 +0000 UTC

如何在 linux 上从源代码安装 ogre3d

  • -2

一般来说,我遇到了一个问题,如何在 Linux 中从源代码安装 ogre3d(在我的例子中是 Astra linux)。

linux
  • 1 个回答
  • 10 Views
Martin Hope
timob256
Asked: 2022-04-29 22:43:42 +0000 UTC

我不明白为什么 qopenglwidget 不起作用

  • 0

我将 qopenglwidget 推到主小部件中,但由于某种原因它没有启动。

我也不能使用 qt 3D 和 Quick 3D

这是代码

对话窗口.h

#ifndef DIALOGOKNO_H
#define DIALOGOKNO_H

#include <QMainWindow>
#include <QFile>
#include <QPushButton>
#include <QLabel>
#include <QSize>

#include <QApplication>
#include <QDesktopWidget>
#include <QRect>
#include <QDebug>
#include <QLineEdit>
#include <QGridLayout>
#include <QSpacerItem>
#include <QObject>
#include "qopenglwidget.h"


class DialogOkno : public QWidget
{
    Q_OBJECT

public:
    DialogOkno(QWidget *parent = 0);
    ~DialogOkno();

protected:
    QFile* file;         // загрузить файл
    QGridLayout* gl_layaout[4];
    QPushButton* b_load; // кнопка для выбора и загрузки файла
    QLabel* l_label[3];
    QLineEdit* le_edit[7];
    QSpacerItem* si_spacer[4];
    QOpenGLWidget *openGLWidget;

    //опен гл
    void initializeGL();
    void paintGL();
    void resizeGL(int width, int height);
};

#endif // DIALOGOKNO_H

对话窗口.cpp

#include "dialogokno.h"

DialogOkno::DialogOkno(QWidget *parent)
    : QWidget(parent)
{
    // обявл элементы
    gl_layaout[0] = new QGridLayout(parent);
    gl_layaout[1] = new QGridLayout(parent);
    gl_layaout[2] = new QGridLayout(parent);

    gl_layaout[3] = new QGridLayout(parent);

    openGLWidget = new QOpenGLWidget(parent);

    l_label[0] = new QLabel(parent);
    l_label[1] = new QLabel(parent);
    l_label[2] = new QLabel(parent);

    le_edit[0] = new QLineEdit(parent);
    le_edit[1] = new QLineEdit(parent);
    le_edit[2] = new QLineEdit(parent);
    le_edit[3] = new QLineEdit(parent);
    le_edit[4] = new QLineEdit(parent);
    le_edit[5] = new QLineEdit(parent);
    le_edit[6] = new QLineEdit(parent);

    // настройки элеметов (стилизация)

    // заполнение элементов
    l_label[0]->setText("hla_global");
    l_label[1]->setText("hla_local");
    l_label[2]->setText("logger");

    le_edit[0]->setText("server_ip_global");
    le_edit[1]->setText("server_port_global");

    le_edit[2]->setText("server_port_local");
    le_edit[3]->setText("server_port_local");

    le_edit[4]->setText("log");
    le_edit[5]->setText("log_period_ms");
    le_edit[6]->setText("log_size_in_mb");

    //разложение элементов по группам

    gl_layaout[0]->addWidget(l_label[0], 0, 0, 1, 1);
    gl_layaout[0]->addWidget(le_edit[0], 1, 0, 1, 1);
    gl_layaout[0]->addWidget(le_edit[1], 2, 0, 1, 1);

    gl_layaout[1]->addWidget(l_label[1], 0, 0, 1, 1);
    gl_layaout[1]->addWidget(le_edit[2], 1, 0, 1, 1);
    gl_layaout[1]->addWidget(le_edit[3], 2, 0, 1, 1);

    gl_layaout[2]->addWidget(l_label[2], 0, 0, 1, 1);
    gl_layaout[2]->addWidget(le_edit[4], 1, 0, 1, 1);
    gl_layaout[2]->addWidget(le_edit[5], 2, 0, 1, 1);
    gl_layaout[2]->addWidget(le_edit[6], 3, 0, 1, 1);


    gl_layaout[3]->addLayout(gl_layaout[0], 0, 0, 1, 1);

    si_spacer[0] = new QSpacerItem(120, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
    gl_layaout[3]->addItem(si_spacer[0], 0, 1, 1, 1);

    gl_layaout[3]->addLayout(gl_layaout[1], 0, 2, 1, 1);
    si_spacer[1] = new QSpacerItem(120, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
    gl_layaout[3]->addItem(si_spacer[1], 0, 3, 1, 1);
    si_spacer[2] = new QSpacerItem(20, 82, QSizePolicy::Minimum, QSizePolicy::Expanding);
    gl_layaout[3]->addItem(si_spacer[2],1, 0, 1, 1);
    gl_layaout[3]->addLayout(gl_layaout[2], 2, 0, 1, 1);
    si_spacer[3] = new QSpacerItem(20, 82, QSizePolicy::Minimum, QSizePolicy::Expanding);
    gl_layaout[3]->addItem(si_spacer[3],3,0);
    gl_layaout[3]->addWidget(openGLWidget, 1, 1, 3, 3);

    this->setLayout(gl_layaout[3]);
}

DialogOkno::~DialogOkno()
{

}

void QOpenGLWidget::initializeGL()
{
    glClearColor(1.0, 1.0, 1.0, 0.0);
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}

void QOpenGLWidget::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glColor3f(0.0, 0.0, 0.0);
    glBegin(GL_QUADS);
    glVertex3f (0.51, 0.51, 0.51);
    glVertex3f (-0.51, 0.51, 0.51);
    glVertex3f (-0.51, -0.51, 0.51);
    glVertex3f (0.51, -0.51, 0.51);
    glEnd();

 }

void QOpenGLWidget::resizeGL(int width, int height)
{
    glViewport(0, 0, width, height);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glMatrixMode(GL_MODELVIEW);
}

主文件

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

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

    QDesktopWidget desktop;
    QRect rect = desktop.availableGeometry(desktop.primaryScreen()); // прямоугольник с размерами экрана
    QPoint center = rect.center(); //координаты центра экрана
 
    qDebug() << "rect.x()/2 " <<rect.y()/2  << "rect.y()/2" << rect.y()/2;
    qDebug() << "center.x()/2 " <<center.y()  << "center.y()/2" << center.y();

    w.resize(center.x(), center.y());
    w.setWindowTitle("программа");
    w.show();

    return a.exec();
}

dialog_window_qmake.pro

#-------------------------------------------------
#
# Project created by QtCreator 2021-11-24T16:28:03
#
#-------------------------------------------------

QT       += core gui opengl

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = dialog_okno_qmake
TEMPLATE = app

# The following define makes your compiler emit warnings if you use
# any feature of Qt which has been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0


SOURCES += \
        main.cpp \
        dialogokno.cpp

HEADERS += \
        dialogokno.h


INCLUDEPATH += $$PWD/glfw_bin/include/GLFW/ \ # добавляем для удобства чтоб напрямую писать
               $$PWD/glew_bin/include/GL/  \  # только название заголовчного файла без полного пути
               $$PWD/stb_image/

HEADERS += \
    glfw_bin/include/GLFW/glfw3.h \
    glfw_bin/include/GLFW/glfw3native.h \
    glew_bin/include/GL/glew.h \

# --- linux ---

unix:!macx: LIBS += -L$$PWD/../../../../usr/lib/x86_64-linux-gnu/ -lOpenGL

INCLUDEPATH += $$PWD/../../../../usr/include/GL
DEPENDPATH += $$PWD/../../../../usr/include/GL

unix:!macx: LIBS += -L$$PWD/../../../../usr/lib/x86_64-linux-gnu/ -lGLEW

INCLUDEPATH += $$PWD/../../../../usr/include/GL
DEPENDPATH += $$PWD/../../../../usr/include/GL

unix:!macx: LIBS += -L$$PWD/../../../../usr/lib/x86_64-linux-gnu/ -lglut

INCLUDEPATH += $$PWD/../../../../usr/include/GL
DEPENDPATH += $$PWD/../../../../usr/include/GL

unix:!macx: LIBS += -L$$PWD/../../../../usr/lib/x86_64-linux-gnu/ -lGLU

INCLUDEPATH += $$PWD/../../../../usr/include/GL
DEPENDPATH += $$PWD/../../../../usr/include/GL

截图_20211129_165752.png

输出:

Запускается /home/dima/dima_project/dialog_okno_qmake/dialog_okno_qmake...
rect.x()/2  0 rect.y()/2 0
center.x()/2  515 center.y()/2 515
QOpenGLContext::makeCurrent() called with non-opengl surface 0x59b7a92e99a0
composeAndFlush: makeCurrent() failed
QOpenGLContext::makeCurrent() called with non-opengl surface 0x59b7a92e99a0
composeAndFlush: makeCurrent() failed
QOpenGLContext::makeCurrent() called with non-opengl surface 0x59b7a92e99a0
composeAndFlush: makeCurrent() failed
QOpenGLContext::makeCurrent() called with non-opengl surface 0x59b7a92e99a0
composeAndFlush: makeCurrent() failed
QOpenGLContext::makeCurrent() called with non-opengl surface 0x59b7a92e99a0
composeAndFlush: makeCurrent() failed
QOpenGLContext::makeCurrent() called with non-opengl surface 0x59b7a92e99a0
composeAndFlush: makeCurrent() failed
QOpenGLContext::makeCurrent() called with non-opengl surface 0x59b7a92e99a0
composeAndFlush: makeCurrent() failed
QOpenGLContext::makeCurrent() called with non-opengl surface 0x59b7a92e99a0
composeAndFlush: makeCurrent() failed
QOpenGLContext::makeCurrent() called with non-opengl surface 0x59b7a92e99a0
composeAndFlush: makeCurrent() failed
QOpenGLContext::makeCurrent() called with non-opengl surface 0x59b7a92e99a0
composeAndFlush: makeCurrent() failed
QOpenGLContext::makeCurrent() called with non-opengl surface 0x59b7a92e99a0
composeAndFlush: makeCurrent() failed
QOpenGLContext::makeCurrent() called with non-opengl surface 0x59b7a92e99a0
composeAndFlush: makeCurrent() failed
QOpenGLContext::makeCurrent() called with non-opengl surface 0x59b7a92e99a0
composeAndFlush: makeCurrent() failed
/home/dima/dima_project/dialog_okno_qmake/dialog_okno_qmake завершился с кодом 0
qt
  • 1 个回答
  • 10 Views
Martin Hope
timob256
Asked: 2022-03-18 16:32:05 +0000 UTC

一个球体怎么能做成沙漏的形状?

  • 0

如何将球体塑造成沙漏?

我只能画一个球体:

void fillVertexArray(void)
{
    int i, j, k;

    k = 0;
    for (j = 0; j <= q; j++)
        for (i = 0; i <= p; i++)
        {
            vertices[k++] = 0.8*(R * cos((float)j /q * PI) * sin(2.0 * (float)i / p * PI));
            vertices[k++] = 1.5*(R * sin((float)j /q * PI) * sin(2.0 * (float)i / p * PI)); //чтобы элипс рисовать
            vertices[k++] = 0.7*(R * cos(2.0 * (float)i / p * PI));
          }
}

在此处输入图像描述

геометрия
  • 1 个回答
  • 10 Views
Martin Hope
timob256
Asked: 2022-03-14 22:31:36 +0000 UTC

领域。怎么画?

  • 1

我正在尝试绘制一个球体。

由这个公式制成

在此处输入图像描述

这是代码:

for (j = 0; j <= q; j++)
{
    for (i = 0; i <= p; i++)
    {
        vertices[k++] = R * cos((float)j /q * PI) * sin(2.0 * (float)i / p * PI);
        vertices[k++] = R * sin((float)j /q * PI) * sin(2.0 * (float)i / p * PI);
        vertices[k++] = R * cos((float)j /q * PI);
      }
}

这是我得到的:

在此处输入图像描述

геометрия
  • 1 个回答
  • 10 Views
Martin Hope
timob256
Asked: 2022-03-13 22:17:07 +0000 UTC

如何将布尔(bool)变量设置为相反的值

  • -2

如何将布尔(bool)变量设置为相反的值?

我可以用这个构造改变值:

if(threadAline)
   {
      threadAline = false;
   }
    else
   {
      threadAline = true;
   }

但是我觉得有点过分了,可以减吗??

问题是免费翻译

c#
  • 1 个回答
  • 10 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5