RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

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

dark_buckwheat's questions

Martin Hope
dark_buckwheat
Asked: 2025-03-18 04:55:13 +0000 UTC

C 语言中动态数组内存分配和函数调用如何交互?

  • 5

我正在用 C 语言编写一个小型控制台游戏。该游戏是一个 3D 扫雷游戏,可以沿轴线调整场地的长度。我将游戏字段存储在一个变量中field,该变量是一个动态数组,其元素是字符串(即长度为 3 的字符数组)。因此该字段是一个二维字符数组(如果我对指针/数组逻辑的理解是正确的)。

在编写程序的过程中,我决定按照“一个功能-一个文件”的原则将代码拆分到多个文件中。我将负责内存分配的那段代码原封不动地移到了函数中int mem(char** field, size_t field_size)。

代码本身:

int mem(char** field, size_t field_size)
{
    size_t i;

    field = malloc(field_size * sizeof(field[0]));
    if (field == NULL) {
        free(field);
        return 1;
    }
    for (i = 0; i < field_size; i++)
        field[i] = NULL;
    for (i = 0; i < field_size; i++) {
        field[i] = malloc(3 * sizeof(field[0][0]));
    }
    for (i = 0; i < field_size; i++) {
        if (field[i] == NULL) {
            free_field(field, field_size);
            return 2;
        }
    }
    return 0;
}

函数free_field(field, field_size)——一个手写函数,用于释放在字段中分配的内存。

问题是,将此逻辑移至单独的文件后,field调用该函数后,默认的 NULL 仍保留在变量中。而且检查发现,函数内部的内存分配是正确的(函数本身内部肯定是被调用的main(),所以问题不在于我忘记写它的调用)。所以我怀疑问题在于field它开始被视为函数本身的内部变量,并且内部的任何更改都不会影响field主程序中的原始变量。

我是否正确理解了这种情况?纠正它的最佳方法是什么?我是否应该重写该函数以便它接收的不是自身field而是对它的引用?

c
  • 2 个回答
  • 38 Views
Martin Hope
dark_buckwheat
Asked: 2022-08-31 11:59:08 +0000 UTC

使用“<”、“>”运算符比较两个布尔变量

  • 0

我需要实现仅显示集合中带有引号的那些元素:

其口语字段值大于指定值

wherespeaking是一个布尔变量,神奇的“给定”也是一个布尔变量的值,但已经由用户输入。换句话说,您需要实现“>”和“<”运算符,但对于布尔变量。

听起来很傻,但这就是工作。所以,需要做点什么。

对我来说足够的最大值是编写以下代码:

List<Dragon> list = new ArrayList<>(collectionManager.getCollection());
list = list.stream().filter(o-> o.getSpeaking().equals(Boolean.valueOf(arg))).toList();

但是这样我只能得到说话等于输入的对象,而不是更少/更多。请帮助并感谢您的时间。

PS可能值得解释一下代码的预期结果。据我了解,如果用户输入true,则程序不应显示任何内容。If false- 仅显示字段值为 的对象speaking true。一般来说,我们还需要一个具有反向操作的函数(改变以前的句子true和false位置),但我可以通过一个例子自己弄清楚。

java
  • 1 个回答
  • 41 Views
Martin Hope
dark_buckwheat
Asked: 2022-08-29 22:19:54 +0000 UTC

如何在json中正确序列化/反序列化具有复杂结构的类对象

  • 0

这个问题很可能已经被问过了,但是我能找到的所有东西都有一点,但仍然不合适。问题的本质:在项目中,我需要能够从文件中保存和读取有关CollectionManager存储HashSet类对象Dragon和更多变量的类对象的数据。实际上,问题在于类对象Dragon还包含其他已经属于类DragonCave和Coordinates. 我需要以某种方式保存我编写/读取的 collectionManager 包含一组龙的信息,这些龙仍然有它们的洞穴和它们的坐标。

还有一个小问题:我在集合管理器和 Dragon 本身中有类型字段java.time.LocalDate,当我尝试使用 Gson 库对它们进行序列化时,抛出异常“无法使字段私有静态最终长 java. time.LocalDate.serialVersionUID 可访问:模块 java.base 不会“打开 java.time”到未命名模块 @6d86b085”

谢谢你花时间陪我。

类和解析器代码: CollectionManager:

package Managers;

import Classes.Dragon;
import Exceptions.FieldNullException;
import Exceptions.IncorrectFieldValueException;

import java.time.LocalDate;
import java.util.HashSet;
import java.util.StringJoiner;


public class CollectionManager {
    private long currentId = 0;
    private HashSet<Dragon> collection;
    private final LocalDate initializationDate;
    private String filePath;

    public CollectionManager(HashSet<Dragon> collection, String filePath) throws IncorrectFieldValueException, FieldNullException {
        this.filePath = filePath;
        this.collection = collection;
        initializationDate = getDate();
    }

    public void setFilePath(String filePath){
        this.filePath = filePath;
    }

    public long getNewId(){
        return currentId++;
    }

    public LocalDate getDate(){
        return LocalDate.now();
    }

    public HashSet<Dragon> getCollection(){
        return collection;
    }

    public void addElement(Dragon element){
        collection.add(element);
    }

    public void removeElementById(Long id){
        collection.removeIf(d -> d.getId().equals(id));
    }

    public void clear(){
        collection.clear();
    }

    public LocalDate getInitializationDate() {
        return initializationDate;
    }

    public String toString() {
        StringJoiner stringJoiner = new StringJoiner("\n");
        if (collection.size() > 0) {
            collection.forEach((k) -> stringJoiner.add(k.toString()));
        } else {
            stringJoiner.add("The collection is empty");
        }
        return stringJoiner.toString();
    }
}

龙:

package Classes;

import Managers.CollectionManager;
import Exceptions.FieldNullException;
import Exceptions.IncorrectFieldValueException;

import java.time.LocalDate;
import java.util.Objects;

public class Dragon implements Comparable<Dragon>{
    private Long id; //Поле не может быть null, Значение поля должно быть больше 0, Значение этого поля должно быть уникальным, Значение этого поля должно генерироваться автоматически
    private String name; //Поле не может быть null, Строка не может быть пустой
    private Coordinates coordinates; //Поле не может быть null
    private java.time.LocalDate creationDate; //Поле не может быть null, Значение этого поля должно генерироваться автоматически
    private int age; //Значение поля должно быть больше 0
    private float wingspan; //Значение поля должно быть больше 0
    private Boolean speaking; //Поле не может быть null
    private Color color; //Поле не может быть null
    private DragonCave cave; //Поле не может быть null


    public Dragon(CollectionManager collectionManager, String name, Coordinates coordinates, int age,
                  float wingspan, Boolean speaking, Color color, DragonCave cave)
            throws FieldNullException, IncorrectFieldValueException {
        if (collectionManager == null) {
            throw new FieldNullException("CollectionManager");
        } else if (name == null) {
            throw new FieldNullException("name");
        } else if (coordinates == null) {
            throw new FieldNullException("coordinates");
        } else if (speaking == null) {
            throw new FieldNullException("speaking");
        } else if (color == null) {
            throw new FieldNullException("color");
        } else if (cave == null) {
            throw new FieldNullException("cave");
        }

        if (name.equals("")) {
            throw new IncorrectFieldValueException("name", name, "not null and not \"\"");
        } else if (age <= 0) {
            throw new IncorrectFieldValueException("age", String.valueOf(age), "greater than 0");
        } else if (wingspan <= 0) {
            throw new IncorrectFieldValueException("wingspan", String.valueOf(wingspan), "greater than 0");
        }

        this.id = collectionManager.getNewId();
        this.name = name;
        this.coordinates = coordinates;
        this.creationDate = collectionManager.getDate();
        this.age = age;
        this.wingspan = wingspan;
        this.speaking = speaking;
        this.color = color;
        this.cave = cave;
    }


    // гетеры
    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public Coordinates getCoordinates() {
        return coordinates;
    }

    public LocalDate getCreationDate() {
        return creationDate;
    }

    public int getAge() {
        return age;
    }

    public float getWingspan() {
        return wingspan;
    }

    public Boolean getSpeaking() {
        return speaking;
    }

    public Color getColor() {
        return color;
    }

    public DragonCave getCave() {
        return cave;
    }


    // сеттеры
    public void setId(Long id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setCoordinates(Coordinates coordinates) {
        this.coordinates = coordinates;
    }

    public void setCreationDate(LocalDate creationDate) {
        this.creationDate = creationDate;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setWingspan(float wingspan) {
        this.wingspan = wingspan;
    }

    public void setSpeaking(Boolean speaking) {
        this.speaking = speaking;
    }

    public void setColor(Color color) {
        this.color = color;
    }

    public void setCave(DragonCave cave) {
        this.cave = cave;
    }

    public int compareTo(Dragon anotherDragon){
        if (name.compareTo(anotherDragon.getName()) != 0) {
            return name.compareTo(anotherDragon.getName());
        }
        else if (Integer.valueOf(age).compareTo(anotherDragon.getAge()) != 0){
            return Integer.valueOf(age).compareTo(anotherDragon.getAge());
        }
        else{
            return Float.valueOf(wingspan).compareTo(anotherDragon.getWingspan());
        }
    }

    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Dragon dragon)) return false;
        return age == dragon.age && Float.compare(dragon.wingspan, wingspan) == 0 && id.equals(dragon.id) &&
                name.equals(dragon.name) && coordinates.equals(dragon.coordinates) &&
                creationDate.equals(dragon.creationDate) && speaking.equals(dragon.speaking) &&
                color == dragon.color && cave.equals(dragon.cave);
    }

    public int hashCode() {
        return Objects.hash(id, name, coordinates, creationDate, age, wingspan, speaking, color, cave);
    }

    public String toString() {
        return "Dragon{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", coordinates=" + coordinates +
                ", creationDate=" + creationDate +
                ", age=" + age +
                ", wingspan=" + wingspan +
                ", speaking=" + speaking +
                ", color=" + color +
                ", cave=" + cave +
                '}';
    }
}

坐标:

package Classes;

import Exceptions.IncorrectFieldValueException;

public class Coordinates {
    private long x; //Значение поля должно быть больше -846
    private double y;

    public Coordinates(long x, double y) throws IncorrectFieldValueException{
        setX(x);
        setY(y);
    }

    public double getY() {
        return y;
    }

    public void setY(double y) {
        this.y = y;
    }

    public long getX() {
        return x;
    }

    public void setX(long x) throws IncorrectFieldValueException {
        if (x < -845) throw new IncorrectFieldValueException("x", String.valueOf(x), "greater than -846");
        this.x = x;
    }

    @Override
    public String toString() {
        return "Coordinates{" +
                "x=" + x +
                ", y=" + y +
                '}';
    }
}

龙穴:

package Classes;

import java.util.Objects;

public class DragonCave {
    private int depth;

    public DragonCave(int depth){
        this.depth = depth;
    }

    public int getDepth() {
        return depth;
    }

    public void setDepth(int depth) {
        this.depth = depth;
    }

    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof DragonCave)) return false;
        DragonCave that = (DragonCave) o;
        return depth == that.depth;
    }

    public int hashCode() {
        return Objects.hash(depth);
    }

    public String toString() {
        return "DragonCave{" +
                "depth=" + depth +
                '}';
    }
}

颜色:

package Classes;

import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

public enum Color {

    BLUE("синий"),
    YELLOW("жёлтый"),
    WHITE("белый");

    private final String colorName;

    private Color(String colorName) {
        this.colorName = colorName;
    }

    private final static Map<String, Color> colors = Arrays.stream(Color.values())
            .collect(Collectors.toMap(k->k.colorName, v->v));

    public static Color getColorByName(String colorName) {
        return colors.get(colorName);
    }

    public String toString() {
        return colorName;
    }
}

解析器:

package Managers;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashSet;
import java.util.Scanner;

import Exceptions.FieldNullException;
import Exceptions.IncorrectFieldValueException;
import com.google.gson.Gson;

public class Parser {
    private Parser() {
    }

    public static CollectionManager convertToJavaObject(File file) throws FieldNullException, IncorrectFieldValueException, FileNotFoundException {
        Gson gson = new Gson();
        // магическим образом получить строку(data) из всего этого
        Scanner scan = new Scanner(file);
        String data = scan.nextLine();
        // это просто отвратительно, но другого способа не придумал
        CollectionManager collectionManager = gson.fromJson(data, CollectionManager.class);
        collectionManager.setFilePath(file.getPath());
        return new CollectionManager(new HashSet<>(), "");
    }

    public static void convertToJSON(CollectionManager data){
        Gson gson = new Gson();
        String json = gson.toJson(data);
        System.out.println(json);
    }
}
java
  • 1 个回答
  • 35 Views
Martin Hope
dark_buckwheat
Asked: 2022-07-13 06:08:03 +0000 UTC

如何按名称选择枚举

  • 1

我是java新手,所以我一直在问愚蠢的问题。这是其中之一。我有这样的枚举:

public enum Color {
    BLUE("синий"),
    YELLOW("жёлтый"),
    WHITE("белый");
}

我真的希望能够神奇地做这样的事情: Color color = Color.magicMethod("синий") 得到一个变量color,其中包含我会得到的相同的东西。 Color color = Color.BLUE 我找到了关于 的信息.valueof(),但是你需要传递“BLUE”而不是“blue”作为参数

感谢您的时间和回复。

java enum
  • 1 个回答
  • 33 Views
Martin Hope
dark_buckwheat
Asked: 2022-07-18 21:34:10 +0000 UTC

是否可以在 __init__(self) 函数中快速将所有类参数转换为 self.<argument> ?

  • 2

现在我正在为我的游戏在 pygame 中编写我的按钮类。该类接收一堆参数作为输入。表格的每个表达式都写起来很不方便self.arg = arg。有什么方法可以将参数列表转换为 self.arg 吗?

比如有这样一种情况:

def __init__(self, surface, color, x, y, length, height, width, text, text_color, font_size):
    self.surface = surface
    self.color = color
    self.x = x
    self.y = y
    pygame.draw.rect(self.surface, self.color, [self.x, self.y, 50, 50])

你想要这样:

def __init__(self, args): #args - список с элементами surface, color, x и y
    super_function(args)
    pygame.draw.rect(self.surface, self.color, [self.x, self.y, 50, 50])
python
  • 1 个回答
  • 10 Views
Martin Hope
dark_buckwheat
Asked: 2022-07-17 22:16:41 +0000 UTC

是否可以通过 Python 创建受密码保护的文本文件并与之交互?

  • 0

我正在用 pygame 编写游戏,所以我决定使用文本文件来保存默认难度和玩家进度设置。显然,如果您不在文本文件中设置密码,玩家将能够更改密码并作弊。当然,我的游戏不是很复杂(字面意思是工兵),作弊也没多大意义,但我仍然不想让玩家拥有操纵文件的能力。这就引出了一个问题:“是否可以通过 Python 创建受密码保护的文本文件并与之交互?”

如果可能的话,我将不胜感激一个实现示例。

python
  • 1 个回答
  • 10 Views
Martin Hope
dark_buckwheat
Asked: 2022-03-10 06:17:53 +0000 UTC

使用 argparse 库解析值时将无效值强制转换为默认值

  • 1

我有一个参数,如果设置它必须取 1 到 100 之间的值。如果未设置或用户输入了不正确的值(例如,109 或 - 12),则应将该值设置为默认值。真正的问题是:如何实现这一目标?

这是完整的代码:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--barbie", type=int, nargs='?', choices=range(0, 100), default=50)
parser.add_argument("--cars", type=int, nargs='?', choices=range(0, 100), default=50)
parser.add_argument("--movie", type=str, nargs='?', choices=['melodrama', 'football', 'other'], default='other')
args = parser.parse_args()
ch = ['melodrama', 'other', 'football']
print(f'boy: {int((100 - args.barbie + args.cars + (ch.index(args.movie) * 50)) / 3)}')
print(f'girl: {int(100 - (100 - args.barbie + args.cars + (ch.index(args.movie) * 50)) / 3)}')
python
  • 1 个回答
  • 10 Views
Martin Hope
dark_buckwheat
Asked: 2022-01-08 06:06:09 +0000 UTC

奇怪的工作QGridLayout

  • 1

我正在编写一个 PyQt5 项目,它由几个窗口组成。项目本身已经处于最后阶段,所以我开始添加窗口布局。除了一扇窗户外,所有窗户都一切顺利。我还是 Qt 的新手,所以花了一天时间寻找解决方案后,我放弃了,来到了这里。

我希望窗口缩放并看起来像这样:

在此处输入图像描述

但是当我尝试缩放窗口时,它看起来像这样:

在此处输入图像描述

出于某种原因,当您尝试拉伸时,窗口QLineEdit只会在长度上增长。我究竟做错了什么?

这是代码:

class Ui_Append(object):
    def setupUi(self, AppendWindow):
        AppendWindow.resize(500, 250)
        self.centralwidget = QtWidgets.QWidget(AppendWindow)
        self.centralwidget.setObjectName("centralwidget")

        self.time = QtWidgets.QTimeEdit(self.centralwidget)
        self.time.setGeometry(QtCore.QRect(50, 85, 170, 40))
        self.time.setObjectName("timeEditWidget")
        font = QtGui.QFont('Times new roman', 16)
        font.setBold(True)
        self.time.setFont(font)
        self.time.setMinimumWidth(170)

        self.lable_1 = QtWidgets.QLabel(self.centralwidget)
        self.lable_1.setGeometry(QtCore.QRect(50, 40, 170, 40))
        self.lable_1.setObjectName("lable_1Widget")
        font = QtGui.QFont('Times new roman', 16)
        font.setBold(True)
        self.lable_1.setFont(font)
        self.lable_1.setText('Выберите время')
        self.lable_1.setMinimumWidth(170)

        self.line = QtWidgets.QLineEdit(self.centralwidget)
        self.line.setGeometry(QtCore.QRect(280, 85, 170, 40))
        self.line.setObjectName("lineEditWidget")
        font = QtGui.QFont('Times new roman', 16)
        font.setBold(True)
        self.line.setFont(font)
        self.line.setMinimumWidth(170)

        self.lable_2 = QtWidgets.QLabel(self.centralwidget)
        self.lable_2.setGeometry(QtCore.QRect(280, 40, 170, 40))
        self.lable_2.setObjectName("lable_2Widget")
        font = QtGui.QFont('Times new roman', 16)
        font.setBold(True)
        self.lable_2.setFont(font)
        self.lable_2.setText('Введите значение')
        self.lable_2.setMinimumWidth(170)

        self.push = QtWidgets.QPushButton(self.centralwidget)
        self.push.setGeometry(QtCore.QRect(160, 160, 180, 40))
        font = QtGui.QFont('Times new roman', 16)
        font.setBold(True)
        self.push.setFont(font)
        self.push.setText('Подтвердить')
        self.push.setMinimumWidth(180)

        AppendWindow.setCentralWidget(self.centralwidget)


class AppendWindow(QMainWindow, Ui_Append):
    def __init__(self, parent=None):
        super(AppendWindow, self).__init__(parent)
        self.parent = parent

        self.setupUi(self)
        self.setWindowTitle('Новая запись')

        self.push.clicked.connect(self.get_value)

        self.grid = QtWidgets.QGridLayout(self.centralwidget)
        self.grid.setContentsMargins(20, 20, 20, 20)
        self.grid.setHorizontalSpacing(20)
        self.grid.setVerticalSpacing(20)
        self.grid.setRowStretch(0, 0)
        self.grid.setRowStretch(1, 1)

        self.grid.addWidget(self.lable_1, 0, 0)
        self.grid.addWidget(self.lable_2, 0, 1)
        self.grid.addWidget(self.time, 1, 0)
        self.grid.addWidget(self.line, 1, 1, 1, 1)
        self.grid.addWidget(self.push, 2, 0, 2, 2, alignment=Qt.AlignCenter)

    def get_value(self):
        value = self.line.text()
        time = self.time.text()
        try:
            con = sqlite3.connect('notes.sqlite')
            cur = con.cursor()
            name = self.parent.comboBox.currentText()
            data = self.parent.label_2.text()
            data = data[-10:]
            id = cur.execute("""SELECT id FROM users WHERE name = ?""", (name,)).fetchall()
            t = cur.execute("""SELECT time FROM note WHERE user = ? AND data = ? AND time = ?""", (id[0][0], data, time)).fetchall()
            if len(t) > 0:
                raise NewException
            if ',' in value and value.count(',') == 1:
                m = value.find(',')
                value = value[:m] + '.' + value[m + 1:]
            value = float(value)
            if value <= 0 or value > 55.5:
                raise Exception
            value = str(value)
            self.parent.save(time, value)
            self.close()
        except NewException:
            msgBox = QMessageBox()
            msgBox.setIcon(QMessageBox.Information)
            msgBox.setWindowTitle("Ошибка")
            msgBox.addButton('ок', QMessageBox.AcceptRole)
            msgBox.setText("Запись на это время уже существует. Пожалуйста измените время"
                           "или очистите день и внесите данные снова")
            msgBox.exec_()
        except Exception:
            msgBox = QMessageBox()
            msgBox.setIcon(QMessageBox.Information)
            msgBox.setWindowTitle("Ошибка")
            msgBox.addButton('ок', QMessageBox.AcceptRole)
            msgBox.setText("Вы некорректно ввели значение. "
                           "Значение должно быть десятичным числом меньшим 55.5 "
                           "и большим 0.0 (Так как значений меньше 0.0 и больше "
                           "55.5 у живого человека быть не может.). Введите другое значение.")
            msgBox.exec_()
python
  • 1 个回答
  • 10 Views
Martin Hope
dark_buckwheat
Asked: 2022-01-05 22:29:25 +0000 UTC

如何制作可缩放的 UI,但小部件的位置设置为精确坐标

  • 1

我英语不好,所以文档对我没有帮助,我在俄语论坛上找不到合适的解决方案。

问题的症结在于我有几个小部件(两个 QLabels,QLineEdit 和 QTimeEdit),我希望它们在调整窗口大小时根据更改进行缩放,但同时它们必须相对于每个小部件保持在相同的位置其他。那些。例如,我希望在两个 QLabel 等之间具有相同的可扩展空白空间。

我附上整个项目的代码,我感兴趣的窗口在AppendWindow类中,它继承了Ui_Append类的UI。

from sys import argv, exit
from os import remove
import sqlite3
from PyQt5.QtWidgets import QApplication, QMainWindow, QInputDialog, QMessageBox, QCalendarWidget
from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(891, 574)
        palette = QtGui.QPalette()
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
        brush = QtGui.QBrush(QtGui.QColor(245, 128, 64))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
        brush = QtGui.QBrush(QtGui.QColor(245, 128, 64))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
        brush = QtGui.QBrush(QtGui.QColor(245, 128, 64))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
        brush = QtGui.QBrush(QtGui.QColor(245, 128, 64))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
        MainWindow.setPalette(palette)
        MainWindow.setStyleSheet("")
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.comboBox = QtWidgets.QComboBox(self.centralwidget)
        self.comboBox.setGeometry(QtCore.QRect(20, 60, 411, 41))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.comboBox.setFont(font)
        self.comboBox.setObjectName("comboBox")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(20, 10, 411, 31))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(18)
        font.setBold(True)
        font.setWeight(75)
        self.label.setFont(font)
        self.label.setWordWrap(False)
        self.label.setObjectName("label")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(20, 120, 411, 41))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton.setFont(font)
        self.pushButton.setObjectName("pushButton")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(500, 100, 361, 41))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(20)
        font.setBold(True)
        font.setWeight(75)
        self.label_2.setFont(font)
        self.label_2.setObjectName("label_2")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(20, 180, 411, 41))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(18)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_2.setFont(font)
        self.pushButton_2.setObjectName("pushButton_2")
        self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_3.setGeometry(QtCore.QRect(20, 240, 411, 41))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(18)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_3.setFont(font)
        self.pushButton_3.setObjectName("pushButton_3")
        self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_4.setGeometry(QtCore.QRect(20, 360, 411, 41))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(18)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_4.setFont(font)
        self.pushButton_4.setObjectName("pushButton_4")
        self.label_4 = QtWidgets.QLabel(self.centralwidget)
        self.label_4.setGeometry(QtCore.QRect(20, 440, 271, 41))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(22)
        font.setBold(True)
        font.setWeight(75)
        self.label_4.setFont(font)
        self.label_4.setObjectName("label_4")
        self.label_5 = QtWidgets.QLabel(self.centralwidget)
        self.label_5.setGeometry(QtCore.QRect(330, 430, 101, 61))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(26)
        font.setBold(True)
        font.setWeight(75)
        self.label_5.setFont(font)
        self.label_5.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
        self.label_5.setObjectName("label_5")
        self.listView = QtWidgets.QListView(self.centralwidget)
        self.listView.setGeometry(QtCore.QRect(500, 150, 361, 351))
        self.listView.setObjectName("listView")
        self.pushButton_5 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_5.setGeometry(QtCore.QRect(500, 20, 361, 51))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        font.setStyleStrategy(QtGui.QFont.PreferAntialias)
        self.pushButton_5.setFont(font)
        self.pushButton_5.setStyleSheet("background-color: rgb(250, 30, 30);")
        self.pushButton_5.setObjectName("pushButton_5")
        self.pushButton_6 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_6.setGeometry(QtCore.QRect(20, 300, 411, 41))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(20)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_6.setFont(font)
        self.pushButton_6.setObjectName("pushButton_6")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 891, 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", "DiaNotes"))
        self.label.setText(_translate("MainWindow", "Текущий пользователь"))
        self.pushButton.setText(_translate("MainWindow", "Создать нового пользователя"))
        self.label_2.setText(_translate("MainWindow", "Дата записи:          01.01.2021"))
        self.pushButton_2.setText(_translate("MainWindow", "Изменить дату"))
        self.pushButton_3.setText(_translate("MainWindow", "Добавить новое значение"))
        self.pushButton_4.setText(_translate("MainWindow", "Построить график"))
        self.label_4.setText(_translate("MainWindow", "Среднее значение:"))
        self.label_5.setText(_translate("MainWindow", "0.0"))
        self.pushButton_5.setText(_translate("MainWindow", "Удалить текущего пользователя"))
        self.pushButton_6.setText(_translate("MainWindow", "Очистить"))




class MyWidget(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.lable_2 = self.label_2
        self.w2 = CalendarWindow(self)
        self.w3 = AppendWindow(self)

        self.pushButton.clicked.connect(self.new_user)

        self.pushButton_5.clicked.connect(self.dellete_user)

        self.pushButton_2.clicked.connect(self.change_data)

        self.pushButton_3.clicked.connect(self.append_note)

        try:
            f = open('notes.sqlite', mode='r')
            f.close()
            con = sqlite3.connect('notes.sqlite')
            cur = con.cursor()
            users = cur.execute("""SELECT name FROM users""").fetchall()
            if len(users) == 0:
                remove('notes.sqlite')
                raise Exception
        except Exception:
            con = sqlite3.connect('notes.sqlite')
            cur = con.cursor()
            try:
                cur.execute("""CREATE TABLE users (name text, id int)""")
            except Exception:
                pass
            cur.execute("""INSERT INTO users VALUES ('default_user', 1)""")
            con.commit()
            try:
                cur.execute("""CREATE TABLE note (user int, data text, time text, value float)""")
            except Exception:
                pass
            cur.execute("""INSERT INTO note VALUES (1, '01.01.2021', '0:00', 5.0)""")
            con.commit()
        con = sqlite3.connect('notes.sqlite')
        cur = con.cursor()
        users = cur.execute("""SELECT name FROM users""").fetchall()
        users = list(map(lambda x: x[0], users))
        self.comboBox.addItems(users)

    def new_user(self):
        name, ok_pressed = QInputDialog.getText(self, "Введите имя",
                                                "Введите имя нового пользователя")
        if ok_pressed:
            self.comboBox.addItem(name)
            self.comboBox.setCurrentText(name)
            con = sqlite3.connect('notes.sqlite')
            cur = con.cursor()
            ind = cur.execute("""SELECT id FROM users""").fetchall()
            ind = 1 + int(ind[-1][-1])
            cur.execute("""INSERT INTO users VALUES (?, ?)""", (name, ind))
            con.commit()

    def dellete_user(self):
        a = []
        for i in range(self.comboBox.count()):
            a.append(self.comboBox.itemText(i))
        if len(a) > 1:
            msgBox = QMessageBox()
            msgBox.setIcon(QMessageBox.Information)
            msgBox.setWindowTitle("Вы уверены?")
            ok = msgBox.addButton('да', QMessageBox.AcceptRole)
            msgBox.addButton('нет', QMessageBox.RejectRole)
            msgBox.setText("Вы действительно хотите удалить нынешнего пользователя?")
            msgBox.exec_()
            if msgBox.clickedButton() == ok:
                ind = self.comboBox.currentIndex()
                us = self.comboBox.currentText()
                con = sqlite3.connect('notes.sqlite')
                cur = con.cursor()
                res = cur.execute("""DELETE FROM note WHERE user = (SELECT id FROM users WHERE name = ?)""", (us,))
                res = cur.execute("""DELETE FROM users WHERE name = ?""", (us,))
                con.commit()
                self.comboBox.removeItem(ind)
        else:
            msgBox = QMessageBox()
            msgBox.setIcon(QMessageBox.Information)
            msgBox.setWindowTitle("Ошибка")
            msgBox.addButton('ок', QMessageBox.AcceptRole)
            msgBox.setText("В списке всего один пользователь, его нельзя удалить. "
                           "Если вы хотите удалить этого пользователя, то создайте "
                           "нового, а после удалите этого")
            msgBox.exec_()

    def change_data(self):
        self.w2.show()

    def append_note(self):
        self.w3.show()


class Ui_Calendar(object):
    def setupUi(self, CalendarWindow):
        CalendarWindow.resize(574, 574)
        self.centralwidget = QtWidgets.QWidget(CalendarWindow)
        self.centralwidget.setObjectName("centralwidget")

        self.calendar = QtWidgets.QCalendarWidget(self.centralwidget)
        self.calendar.setGeometry(QtCore.QRect(37, 74, 500, 500))
        self.calendar.setObjectName("calendarWidget")

        self.pushButton_7 = QtWidgets.QPushButton("Подтвердить", self.centralwidget)
        self.pushButton_7.setGeometry(QtCore.QRect(207, 25, 160, 40))
        self.pushButton_7.setObjectName("pushButton_7")
        font = QtGui.QFont('Times new roman', 16)
        font.setBold(True)
        self.pushButton_7.setFont(font)

        CalendarWindow.setCentralWidget(self.centralwidget)


class CalendarWindow(QMainWindow, Ui_Calendar):
    def __init__(self, parent=None):
        super(CalendarWindow, self).__init__(parent)
        self.parent = parent

        self.setupUi(self)
        self.setWindowTitle('Выберите дату')

        self.pushButton_7.clicked.connect(self.change)

    def change(self):
        data = self.calendar.selectedDate().getDate()
        data = list(data)
        for i in range(len(data)):
            if data[i] < 10:
                data[i] = '0' + str(data[i])
        data = str(data[2]) + '.' + str(data[1]) + '.' + str(data[0])
        self.parent.lable_2.setText('Дата записи:          ' + data)


class Ui_Append(object):
    def setupUi(self, AppendWindow):
        AppendWindow.resize(500, 400)
        self.centralwidget = QtWidgets.QWidget(AppendWindow)
        self.centralwidget.setObjectName("centralwidget")

        self.time = QtWidgets.QTimeEdit(self.centralwidget)
        self.time.setGeometry(QtCore.QRect(50, 75, 170, 50))
        self.time.setObjectName("timeEditWidget")
        font = QtGui.QFont('Times new roman', 16)
        font.setBold(True)
        self.time.setFont(font)

        self.lable_1 = QtWidgets.QLabel(self.centralwidget)
        self.lable_1.setGeometry(QtCore.QRect(50, 40, 170, 40))
        self.lable_1.setObjectName("lable_1Widget")
        font = QtGui.QFont('Times new roman', 16)
        font.setBold(True)
        self.lable_1.setFont(font)
        self.lable_1.setText('Выберите время')

        self.line = QtWidgets.QLineEdit(self.centralwidget)
        self.line.setGeometry(QtCore.QRect(280, 75, 170, 50))
        self.line.setObjectName("lineEditWidget")
        font = QtGui.QFont('Times new roman', 16)
        font.setBold(True)
        self.line.setFont(font)

        self.lable_2 = QtWidgets.QLabel(self.centralwidget)
        self.lable_2.setGeometry(QtCore.QRect(280, 40, 170, 40))
        self.lable_2.setObjectName("lable_2Widget")
        font = QtGui.QFont('Times new roman', 16)
        font.setBold(True)
        self.lable_2.setFont(font)
        self.lable_2.setText('Введите значение')

        AppendWindow.setCentralWidget(self.centralwidget)


class AppendWindow(QMainWindow, Ui_Append):
    def __init__(self, parent=None):
        super(AppendWindow, self).__init__(parent)
        self.parent = parent

        self.setupUi(self)
        self.setWindowTitle('Новая запись')



if __name__ == '__main__':
    app = QApplication(argv)
    ex = MyWidget()
    ex.show()
    exit(app.exec_())
python
  • 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