RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

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

Владимир's questions

Martin Hope
Владимир
Asked: 2023-12-28 19:31:06 +0000 UTC

如何在 Kotlin 中的 2D 数组的每一列中随机选择 1 个值?

  • 5

如何在Kotlin中随机选择二维数组的每一列1个值并将结果写入新数组?

鉴于:

val table = Array(3, { Array(3, {0}) })
table[0] = arrayOf(1, 2, 3)     // первая строка таблицы
table[1] = arrayOf(4, 5, 6)     // вторая строка таблицы
table[2] = arrayOf(7, 8, 9)     // третья строка таблицы

例如,输出应如下所示:1,8,6

kotlin
  • 2 个回答
  • 17 Views
Martin Hope
Владимир
Asked: 2023-10-16 01:36:20 +0000 UTC

如何使用numpy在二维数组的每一列中随机选择1个值?

  • 6

如何使用numpy在 2D 数组的每一列中随机选择 1 个值?

鉴于:

array = [
    [1, 2, 3],
    [4, 5, 6], 
    [7, 8, 9]
        ]

例如,输出应如下所示:1,8,6

python
  • 4 个回答
  • 36 Views
Martin Hope
Владимир
Asked: 2023-07-08 04:07:41 +0000 UTC

如何在PyQt中无限循环中显示滑块值?

  • 5

此代码允许您显示滑块的值。但是,需要在代码中更改哪些内容才能无限循环地显示滑块的值呢?

主要.py

import sys

from PyQt6.QtWidgets import QApplication, QMainWindow
from PyQt6.uic import loadUi


class SliderValue(QMainWindow):
    def __init__(self):
        super(SliderValue, self).__init__()
        loadUi("slider_test.ui", self)

        self.ui_horizontalSlider.valueChanged.connect(self.updateValue)

    def updateValue(self, value):
        print(value)

    # Вывод в бесконечном цикле значения с ползунка
    # ?? def printValueInLoop(self):
    # ??     while(True):
    # ??         self.updateValue()



if __name__ == '__main__':
    app = QApplication(sys.argv)
    SV = SliderValue()
    SV.show()
    sys.exit(app.exec())

slider_test.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>800</width>
    <height>600</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <widget class="QSlider" name="ui_horizontalSlider">
    <property name="geometry">
     <rect>
      <x>330</x>
      <y>240</y>
      <width>160</width>
      <height>22</height>
     </rect>
    </property>
    <property name="orientation">
     <enum>Qt::Horizontal</enum>
    </property>
   </widget>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>800</width>
     <height>26</height>
    </rect>
   </property>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>
pyqt5
  • 1 个回答
  • 9 Views
Martin Hope
Владимир
Asked: 2023-04-22 03:31:58 +0000 UTC

如何访问另一个模块中的 PyQt6 中的函数

  • 6

这个最小的例子展示了如何通过切换单选按钮来激活/停用旋转框。

随着时间的推移,代码会增长并且需要分解。

帮助将方法移动spinBoxSetEnabled_1()到spinBoxSetEnabled_2()单独的文件中。

主程序

import sys

from PyQt6.QtWidgets import QMainWindow, QApplication
from PyQt6.uic import loadUi


class New(QMainWindow):
    def __init__(self):
        super(New, self).__init__()
        loadUi("Test.ui", self)

        self.RB_1.setChecked(True)
        self.RB_1.clicked.connect(self.spinBoxSetEnabled_1)
        self.SB_1.setEnabled(True)

        self.RB_2.setChecked(False)
        self.RB_2.clicked.connect(self.spinBoxSetEnabled_2)

    def spinBoxSetEnabled_1(self):
        self.SB_1.setEnabled(True)
        self.SB_2.setEnabled(False)

    def spinBoxSetEnabled_2(self):
        self.SB_1.setEnabled(False)
        self.SB_2.setEnabled(True)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = New()
    window.show()
    sys.exit(app.exec())

测试.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>732</width>
    <height>539</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <widget class="QGroupBox" name="groupBox">
    <property name="geometry">
     <rect>
      <x>10</x>
      <y>0</y>
      <width>701</width>
      <height>491</height>
     </rect>
    </property>
    <property name="title">
     <string>GroupBox</string>
    </property>
    <widget class="QSpinBox" name="SB_1">
     <property name="enabled">
      <bool>false</bool>
     </property>
     <property name="geometry">
      <rect>
       <x>40</x>
       <y>40</y>
       <width>131</width>
       <height>61</height>
      </rect>
     </property>
    </widget>
    <widget class="QSpinBox" name="SB_2">
     <property name="enabled">
      <bool>false</bool>
     </property>
     <property name="geometry">
      <rect>
       <x>200</x>
       <y>40</y>
       <width>131</width>
       <height>61</height>
      </rect>
     </property>
    </widget>
    <widget class="QRadioButton" name="RB_1">
     <property name="geometry">
      <rect>
       <x>50</x>
       <y>160</y>
       <width>95</width>
       <height>20</height>
      </rect>
     </property>
     <property name="text">
      <string>1</string>
     </property>
    </widget>
    <widget class="QRadioButton" name="RB_2">
     <property name="geometry">
      <rect>
       <x>210</x>
       <y>160</y>
       <width>95</width>
       <height>20</height>
      </rect>
     </property>
     <property name="text">
      <string>2</string>
     </property>
    </widget>
   </widget>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>732</width>
     <height>26</height>
    </rect>
   </property>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>
python
  • 1 个回答
  • 26 Views
Martin Hope
Владимир
Asked: 2022-07-15 06:45:20 +0000 UTC

填充后如何打印整个HashMap表?[关闭]

  • -1
关闭 这个问题是题外话。目前不接受回复。

该问题是由不再复制的问题或错字引起的。虽然类似问题可能与本网站相关,但该问题的解决方案不太可能帮助未来的访问者。通常可以通过在发布问题之前编写和研究一个最小程序来重现问题来避免此类问题。

3 个月前关闭。

改进问题

类中填满后调用打印整张表的方法需要在类Manager中改正什么?我的问题是记录被覆盖,只显示最后一个。我想得到这三个。MainHashMap

Main:

public class Main {

    public static void main(String[] args) {
        Manager manager = new Manager();
        manager.createNewTask("Задача 1", "Desc 1", TaskStatus.NEW);
        manager.createNewTask("Задача 2", "Desc 2", TaskStatus.IN_PROGRESS);
        manager.createNewTask("Задача 3", "Desc 3", TaskStatus.DONE);

        /*
        !!!!  Тут метод должен вывести на печать весь allTacks  !!!!
          Но у меня всегда выводится только последняя запись при вызове:
        System.out.println(manager.getAllTacks());
        */
    }
}

Task:

import java.util.Objects;


public class Task {
    private static long id;
   private String name;
    private String description;
    private TaskStatus status;

    public Task(String name, String description, TaskStatus status) {
        this.name = name;
        this.description = description;
        this.status = status;
    }

    public static long getId() {
        return id;
    }

    public TaskStatus getStatus() {
        return status;
    }

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

    public void setDescription(String description) {
        this.description = description;
    }

    public void setStatus(TaskStatus status) {
        this.status = status;
    }

    public static void setId(long id) {
        Task.id = id;
    }

    public String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }

    @Override
    public String toString() {
        return "Task{" +
                "name='" + name + '\'' +
                ", description='" + description + '\'' +
                ", status=" + status +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || this.getClass() != o.getClass()) return false;
        Task task = (Task) o;
        return Objects.equals(task.id, this.id) &&
                Objects.equals(task.name, this.name) &&
                Objects.equals(task.description, this.description) &&
                Objects.equals(task.status, this.status);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, description, status);
    }
}

Manager:

import java.util.*;

public class Manager {
    private HashMap<Integer, Task> allTacks;


    public Manager() {
        this.allTacks = new HashMap<>();
    }


    public void createNewTask(String name, String description, TaskStatus status) {
        allTacks.put(Task.getId(), new Task(name, description, status));
    }

    public HashMap<Integer, Task> getAllTacks() {
        return allTacks;
    }
}

TaskStatus:

public enum TaskStatus {
    NEW,
    IN_PROGRESS,
    DONE
}
java
  • 1 个回答
  • 50 Views
Martin Hope
Владимир
Asked: 2022-06-23 17:50:53 +0000 UTC

如何过滤文件列表?

  • -1

该程序可以访问该文件夹并显示文件列表以供进一步使用。

Папка resources -- файл x.111.txt
          |------- файл x.112.txt
          |------- файл x.113.txt
          |------- файл y.111.txt

如何正确编写过滤器以从列表中排除文件y.111.txt(通过“y”符号)?

主.java

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {

    public static void main(String[] args) throws IOException {
        Path path = Paths.get("resources");
        List<Path> paths = listFiles(path);
        System.out.println(paths);
    }

    public static List<Path> listFiles(Path path) throws IOException {
        List<Path> result;
        try (Stream<Path> walk = Files.walk(path)) {
            result = walk.filter(Files::isRegularFile)
                    .collect(Collectors.toList());
        }
        return result;
    }
}
java
  • 1 个回答
  • 52 Views
Martin Hope
Владимир
Asked: 2022-06-18 01:42:58 +0000 UTC

如何访问.csv文件中的列值?

  • 0

作业说:当处理已知格式的字符串时,使用 split() 方法很方便。它在分隔符处拆分原始字符串并返回一个字符串数组。例如,要分割我们的行,我们需要从文件中逐行调用带有 System.lineSeparator() 参数的方法。此函数返回字符串的结尾:

String[] lines = fileContents.split(System.lineSeparator());

现在我们有一组字符串。仍然需要使用相同的方法拆卸它们中的每一个。除法将在符号“,”上进行:

String[] lineContents = line.split(",");

这将允许您引用字符串中的特定值。

现在问题本身:

如何在我的代码中使用所有这些来访问xxx.csv文件中的值以进一步使用它们(例如,获取 sum_of_one 列的总和)?:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {
    public static void main(String[] args) {
        System.out.println(readFileContents("xxx.csv"));
    }

    private static String readFileContents(String filename){
    Path filePath = Paths.get(filename);
    try {
        return Files.readString(filePath);
        } catch (IOException e) {
            System.out.println("Невозможно прочитать файл. Возможно, файл не находится в нужной директории.");
        }
    }
}

xxx.csv

item_name,is_expense,quantity,sum_of_one
Коньки,TRUE,50,2000
Новогодняя ёлка,TRUE,1,100000
Ларёк с кофе,TRUE,3,50000
Аренда коньков,FALSE,1000,180
Продажа билетов,FALSE,3500,300
Продажа кофе,FALSE,2421,150
java
  • 2 个回答
  • 199 Views
Martin Hope
Владимир
Asked: 2022-06-17 19:46:45 +0000 UTC

如何正确地将代码移动到单独的方法并调用该方法?

  • 0

程序打开 .csv 文件并显示其内容。

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {
    public static void main(String[] args) {

        Path filePath = Paths.get("xxx.csv");
        try {
            String content = Files.readString(filePath);
            System.out.println(content);
        } catch (IOException e) {
            System.out.println("Невозможно прочитать файл. Возможно, файл не находится в нужной директории.");      
        }
    }
}

如何将这段代码移动到一个单独的方法中,如下所示:

private String readFileContentsOrNull(String path) 
{
    try {
        return Files.readString(Path.of(path));
    } catch (IOException e) {
        System.out.println("Невозможно прочитать файл. Возможно, файл не находится в нужной директории.");
        return null;
    }
}

以及如何称呼它?

java
  • 0 个回答
  • 0 Views
Martin Hope
Владимир
Asked: 2022-06-15 03:40:38 +0000 UTC

如何在HashMap表中找到订单量最高的客户?

  • -1

在 getMaxOrderCustomerName() 方法中嵌套循环以查找订单数量最多的客户的正确方法是什么?

public class Main {

    public static void main(String[] args) {
        OrdersManager ordersManager = new OrdersManager();

        ordersManager.printAllOrders();
        System.out.println("Всего заказов на сумму: " + ordersManager.getOrdersSum());

        String maxOrderCustomerName = ordersManager.getMaxOrderCustomerName();
        System.out.println("Самая большая сумма заказов у " + maxOrderCustomerName);
        ordersManager.printCustomerOrders(maxOrderCustomerName);

        ordersManager.removeUnprofitableOrders();
    }
}


import java.util.ArrayList;
import java.util.HashMap;

public class OrdersManager {
    HashMap<String, ArrayList<Double>> customersOrders;

    public OrdersManager() {
        customersOrders = new HashMap<>();
        ArrayList<Double> orders = new ArrayList<>();
        orders.add(154.43);
        orders.add(5453.98);
        orders.add(8776.65);
        customersOrders.put("Иван И.", orders);

        orders = new ArrayList<>();
        orders.add(25343.54);
        orders.add(420.50);
        customersOrders.put("Ольга С.", orders);

        orders = new ArrayList<>();
        orders.add(325.90);
        customersOrders.put("Александр Т.", orders);

        orders = new ArrayList<>();
        orders.add(253.54);
        orders.add(420.50);
        customersOrders.put("Александр Р.", orders);

        orders = new ArrayList<>();
        orders.add(780.54);
        orders.add(420.50);
        orders.add(36343.54);
        orders.add(2000.50);
        customersOrders.put("Екатерина О.", orders);
    }

    void printAllOrders() {
        for (String name : customersOrders.keySet()) { // Цикл должен пройтись по ключам
            System.out.println("Заказы " + name + ":");
            ArrayList<Double> value = customersOrders.get(name);
            System.out.println(value);
        }
    }

    double getOrdersSum() {
        double sum = 0;
        for (ArrayList<Double> orders : customersOrders.values()) { // Здесь должен быть обход по значениям
            for (double orderPrice : orders) {
                sum += orderPrice;
            }
        }
        return sum;
    }

    void printCustomerOrders(String customerName) {
        if (customersOrders.containsKey(customerName)) { // Проверьте, есть ли указанный ключ в таблице
            System.out.println("Заказы " + customerName + ":");
            System.out.println(customersOrders.get(customerName));
        }
    }

    String getMaxOrderCustomerName() {
        double maxOrder = 0;
        String customerName = "";

       // for (Double value : customersOrders.values()) {
       //     if (value > maxOrder) {
       //         maxOrder = value;
       //    }
       // } 

        return customerName;
    }

    void removeUnprofitableOrders() {
        ArrayList<String> names = new ArrayList<>();// Создайте список клиентов с заказами меньше 5000​
        // Наполните список names
        for (String name : customersOrders.keySet()) {
            double ordersSum = 0;

            for (Double orders : customersOrders.get(name)) {
                ordersSum += orders;
            }
            if (ordersSum < 5000) {
                names.add(name);
            }
        }

        for (String name : names) {
            if (customersOrders.containsKey(name)) {
                customersOrders.remove(name);
                System.out.println("Клиента " + name + " больше нет в таблице.");
            }
        }
    }
}
java
  • 1 个回答
  • 98 Views
Martin Hope
Владимир
Asked: 2022-06-11 18:59:31 +0000 UTC

计数器正常工作的代码应该是什么样的?

  • -1

该计划应保留租用和归还滑板车的记录。但是当您单击第 2 项的选择时,程序会添加一次踏板车。随后选择第 2 项不会添加另一个踏板车。代码中需要更正哪些内容才能使计数器正常工作?

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Сколько самокатов доступно для аренды?");
        int availableScooters = scanner.nextInt(); // Считайте количество доступных самокатов с клавиатуры

        System.out.println("Сколько самокатов арендовано?");
        int scootersInUse = scanner.nextInt(); // Считайте число арендованных самокатов с клавиатуры

        Scooter scooter = new Scooter(availableScooters, scootersInUse); // Создайте новый объект класса Scooter

        System.out.println("Что вы хотите сделать?");
        System.out.println("1 -- Узнать текущую стоимость проката");
        System.out.println("2 -- Выдать самокат");
        System.out.println("3 -- Принять самокат");
        System.out.println("4 -- Завершить работу");

        while (true) { // реализуйте непрерывный ввод команд
            System.out.println("Введите команду:");
            int command = scanner.nextInt(); // Считайте команду с клавиатуры

            if (command == 1) {
                scooter.getPrice(scootersInUse, availableScooters); // Вызовите нужный метод класса Scooter
            } else if (command == 2) {
                scooter.rentScooter(scootersInUse, availableScooters); // Вызовите нужный метод класса Scooter
            } else if (command == 3) {
                scooter.returnScooter(scootersInUse, availableScooters); // Вызовите нужный метод класса Scooter
            } else if (command == 4) {
                System.out.println("Сеанс работы завершён!");
                break; // Завершите ввод команд и работу программы
            } else {
                System.out.println("Введён неверный код команды.");
            }
        }
    }
}

class Scooter {
    static int availableScooters;
    static int scootersInUse;
    int defaultPrice = 8; // Цена аренды по умолчанию
    int additionalPrice = 5; // Добавочная стоимость при повышенном спросе

    public Scooter(int inputAvailableScooters, int inputScootersInUse) {
        availableScooters = inputAvailableScooters;
        scootersInUse = inputScootersInUse;
    }

    public void getPrice(int scootersInUse, int availableScooters) {
        if (availableScooters == 0) { // Проверьте, есть ли доступные самокаты
            System.out.println("Нет доступных самокатов.");
        } else {
            int currentPrice = defaultPrice + additionalPrice * ((scootersInUse + 1) / availableScooters); // Посчитайте текущую стоимость проката
            System.out.println("Текущая стоимость проката: " + currentPrice + " руб/мин");
        }
    }

    public void rentScooter(int scootersInUse, int availableScooters) {
        if (availableScooters == 0) { // Проверьте, есть ли доступные самокаты
            System.out.println("Доступных самокатов не осталось.");
        } else {
            int currentPrice = defaultPrice + additionalPrice * ((++scootersInUse) / availableScooters--); /* Посчитайте текущую стоимость проката,
            увеличьте число арендованных самокатов и уменьшите число доступных */
            System.out.println("Выдайте самокат по цене " + currentPrice + " руб/мин");
            System.out.println("Самокатов в аренде: " + scootersInUse);
            System.out.println("Самокатов доступно: " + availableScooters);
        }
    }

    public void returnScooter(int scootersInUse, int availableScooters) {
        if (scootersInUse == 0){ // Проверьте, есть ли самокаты в аренде
            System.out.println("Все самокаты уже возвращены.");
        } else {
            // Уменьшите число арендованных самокатов и увеличьте число доступных
            System.out.println("Самокат принят.");
            System.out.println("Самокатов в аренде: " + scootersInUse);
            System.out.println("Самокатов доступно: " + availableScooters);
        }
    }
}
java
  • 2 个回答
  • 10 Views
Martin Hope
Владимир
Asked: 2022-09-08 14:45:18 +0000 UTC

程序应该输出一个月的下雨天数。需要添加什么才能使计数器正常工作?

  • -1
public class Praktikum {
    public static void main(String[] args) {
        WeatherCalendar calendar = new WeatherCalendar("Октябрь", 31);
        String[] octoberWeather = new String[]{
                "Солнечно",
                "Дождь",
                "Пасмурно",
                "Дождь",
                "Дождь",
                "Облачно",
                "Солнечно",
                "Дождь",
                "Пасмурно",
                "Солнечно",
                "Солнечно",
                "Облачно",
                "Солнечно",
                "Дождь",
                "Пасмурно",
                "Солнечно",
                "Солнечно",
                "Облачно",
                "Облачно",
                "Облачно",
                "Облачно",
                "Дождь",
                "Дождь",
                "Облачно",
                "Солнечно",
                "Дождь",
                "Пасмурно",
                "Дождь",
                "Солнечно",
                "Солнечно",
                "Солнечно",
                "Солнечно",
                "Облачно"
        };
        int rainyDays = 0;

        for (int i = 0; i < calendar.numberOfDays; i++) {
            if (octoberWeather[i].equals("Дождь")) {
                calendar.addRainyDay(rainyDays);
            }
        }

        // Проверить, был ли месяц дождливым. Если да - установить значение isRainyMonth
        if (calendar.rainyDays > 15) {
            calendar.isRainyMonth = true;
        }

        System.out.println(calendar.month + " " + calendar.year + " года. "
                + calendar.rainyDays + " дней шёл дождь.");

        // Проверить значение isRainyMonth
        if (calendar.isRainyMonth) {
            System.out.println("Это был дождливый месяц.");
        } else {
            System.out.println("Этот месяц был довольно сухим.");
        }
    }
}

class WeatherCalendar {
    String month;
    int numberOfDays;

    int rainyDays;
    boolean isRainyMonth = false;
    int year = 2020;

    public WeatherCalendar(String monthName, int monthNumberOfDays) {
        month = monthName;
        numberOfDays = monthNumberOfDays;
    }

    public void addRainyDay(int rainyDays) {
        rainyDays ++;
    }
}
java
  • 1 个回答
  • 10 Views
Martin Hope
Владимир
Asked: 2022-06-03 20:18:45 +0000 UTC

如何在 PyQt5 中独立运行两个长时间运行的脚本?

  • 2

有两个按钮(1 和 2)。

单击按钮 1 将启动script_1.py文件,该文件执行一项长任务。

按钮 2 启动script_2.py,它也执行一个长任务。

问题是在script_1.py被执行之前,按钮 1 不会运行script_2.py。需要添加什么以使按钮 2 不等待script_1.py完成执行?

主文件

import sys
from PyQt5.QtWidgets import QDialog, QApplication
from PyQt5.uic import loadUi
import os


class New(QDialog):
    def __init__(self):
        super(New, self).__init__()

        loadUi("form.ui", self)

        self.FB_1.clicked.connect(self.file_1)
        self.FB_2.clicked.connect(self.file_2)

    def file_1(self):
        os.system("script_1.py")

    def file_2(self):
        os.system("script_2.py")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = New()
    window.show()
    sys.exit(app.exec_())

表单.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Dialog</class>
 <widget class="QDialog" name="Dialog">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>160</width>
    <height>280</height>
   </rect>
  </property>
  <property name="minimumSize">
   <size>
    <width>160</width>
    <height>280</height>
   </size>
  </property>
  <property name="maximumSize">
   <size>
    <width>160</width>
    <height>280</height>
   </size>
  </property>
  <property name="windowTitle">
   <string>Dialog</string>
  </property>
  <property name="styleSheet">
   <string notr="true">background-color: qradialgradient(spread:pad, cx:0.5, cy:0.5, radius:0.5, fx:0.5, fy:0.5, stop:0 rgba(0, 223, 255, 255), stop:1 rgba(25, 58, 73, 255));</string>
  </property>
  <property name="sizeGripEnabled">
   <bool>false</bool>
  </property>
  <property name="modal">
   <bool>false</bool>
  </property>
  <widget class="QGroupBox" name="groupBox_7">
   <property name="geometry">
    <rect>
     <x>5</x>
     <y>5</y>
     <width>150</width>
     <height>270</height>
    </rect>
   </property>
   <property name="minimumSize">
    <size>
     <width>0</width>
     <height>270</height>
    </size>
   </property>
   <property name="maximumSize">
    <size>
     <width>16777215</width>
     <height>270</height>
    </size>
   </property>
   <property name="styleSheet">
    <string notr="true">background-color: qradialgradient(spread:pad, cx:0.5, cy:0.5, radius:0.5, fx:0.5, fy:0.5, stop:0 rgba(0, 223, 255, 255), stop:0.9801 rgba(29, 34, 36, 255));</string>
   </property>
   <property name="title">
    <string/>
   </property>
   <widget class="QVideoWidget" name="VIDEO_widget" native="true">
    <property name="geometry">
     <rect>
      <x>0</x>
      <y>0</y>
      <width>150</width>
      <height>270</height>
     </rect>
    </property>
    <property name="sizePolicy">
     <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
      <horstretch>0</horstretch>
      <verstretch>0</verstretch>
     </sizepolicy>
    </property>
    <property name="minimumSize">
     <size>
      <width>150</width>
      <height>270</height>
     </size>
    </property>
    <property name="maximumSize">
     <size>
      <width>150</width>
      <height>270</height>
     </size>
    </property>
    <property name="styleSheet">
     <string notr="true">background-color: rgb(0, 0, 0);</string>
    </property>
    <widget class="QPushButton" name="FB_1">
     <property name="geometry">
      <rect>
       <x>10</x>
       <y>20</y>
       <width>60</width>
       <height>40</height>
      </rect>
     </property>
     <property name="maximumSize">
      <size>
       <width>100</width>
       <height>50</height>
      </size>
     </property>
     <property name="font">
      <font>
       <pointsize>9</pointsize>
       <weight>75</weight>
       <bold>true</bold>
      </font>
     </property>
     <property name="styleSheet">
      <string notr="true">QPushButton {
    background-color: qradialgradient(spread:pad, cx:0.5, cy:0.5, radius:0.5, fx:0.5, fy:0.5, stop:0 rgba(107, 134, 255, 255), stop:1 rgba(185, 241, 255, 255));   
    border-color: #8F8F91;
    border-style: outset;
    border-width: 4px;
    border-radius: 10px;
}


QPushButton:default {
    border-color: royalblue; /* make the default button prominent */
}
QPushButton:pressed {
    background-color: white;
    border-color: qradialgradient(spread:pad, cx:0.5, cy:0.5, radius:0.5, fx:0.5, fy:0.5, stop:  0.199005 rgba(29, 43, 65, 255), stop:1 rgba(255, 255, 255, 255));
    border-style: inset;
}</string>
     </property>
     <property name="text">
      <string>1</string>
     </property>
     <property name="iconSize">
      <size>
       <width>40</width>
       <height>40</height>
      </size>
     </property>
    </widget>
    <widget class="QPushButton" name="FB_2">
     <property name="geometry">
      <rect>
       <x>80</x>
       <y>20</y>
       <width>60</width>
       <height>40</height>
      </rect>
     </property>
     <property name="maximumSize">
      <size>
       <width>100</width>
       <height>50</height>
      </size>
     </property>
     <property name="font">
      <font>
       <pointsize>9</pointsize>
       <weight>75</weight>
       <bold>true</bold>
      </font>
     </property>
     <property name="styleSheet">
      <string notr="true">QPushButton {
    background-color: qradialgradient(spread:pad, cx:0.5, cy:0.5, radius:0.5, fx:0.5, fy:0.5, stop:0 rgba(107, 134, 255, 255), stop:1 rgba(185, 241, 255, 255));   
    border-color: #8F8F91;
    border-style: outset;
    border-width: 4px;
    border-radius: 10px;
}


QPushButton:default {
    border-color: royalblue; /* make the default button prominent */
}
QPushButton:pressed {
    background-color: white;
    border-color: qradialgradient(spread:pad, cx:0.5, cy:0.5, radius:0.5, fx:0.5, fy:0.5, stop:  0.199005 rgba(29, 43, 65, 255), stop:1 rgba(255, 255, 255, 255));
    border-style: inset;
}</string>
     </property>
     <property name="text">
      <string>2</string>
     </property>
     <property name="iconSize">
      <size>
       <width>40</width>
       <height>40</height>
      </size>
     </property>
    </widget>
   </widget>
  </widget>
 </widget>
 <customwidgets>
  <customwidget>
   <class>QVideoWidget</class>
   <extends>QWidget</extends>
   <header>PyQt5.QtMultimediaWidgets</header>
   <container>1</container>
  </customwidget>
 </customwidgets>
 <resources/>
 <connections/>
</ui>
python
  • 1 个回答
  • 10 Views
Martin Hope
Владимир
Asked: 2022-04-25 20:44:16 +0000 UTC

如何在 PyQt5 中使用 QProcess 运行文件?

  • 2

如何在PyQt5中运行文件QProcess?

按下按钮时,没有任何反应。

test_QProsess.py

import sys
import subprocess

from PyQt5 import Qt
from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton
from PyQt5.QtCore import QProcess

class StartProcess(QMainWindow):
    def __init__(self):
        super(StartProcess, self).__init__()
        self.setGeometry(50, 50, 500, 300)
        self.setWindowTitle('Главное окно')
        self.sprocess()

    def sprocess(self):
        btn_run = QPushButton('Пуск', self)
        filepath = "hello.py"
        btn_run.clicked.connect(lambda checked, arg=filepath: self.execute(arg))

        self.show()

    def execute(self, filepath):
        QProcess.startDetached(filepath)

if not QApplication.instance():
    app = QApplication(sys.argv)
else:
    app = QApplication.instance()

GUI = StartProcess()
app.exec_()

你好.py

print('Привет!')
python
  • 1 个回答
  • 10 Views
Martin Hope
Владимир
Asked: 2022-09-14 21:40:04 +0000 UTC

如何使用 PyQt5 中的单选按钮切换 QMediaPlayer 播放列表中的文件

  • 1

该程序有 2 个视频小部件和 2 个单选按钮。在程序中,指定四个视频文件或图像的路径。

该程序的目的是在按下按钮时播放 1 号和 3 号文件RB_1,以及在RB_22 号和 4 号文件时播放。

但是,该程序随机播放文件。然而,RB_1我把它激活了,这样当程序启动时,文件会自动启动,但启动时缺少一些东西。

主文件

import sys
from PyQt5 import QtCore
from PyQt5.QtMultimedia import QMediaPlayer, QMediaPlaylist, QMediaContent
from PyQt5.QtCore import pyqtSlot
from PyQt5.Qt import Qt
from PyQt5.QtWidgets import QDialog, QApplication
from PyQt5.uic import loadUi


class New(QDialog):
    def __init__(self):
        super(New, self).__init__()

        loadUi("RB_Video.ui", self)

        self.RB_1.clicked.connect(self.func_1)
        self.RB_1.setLayoutDirection(Qt.RightToLeft)
        self.RB_1.setChecked(True)

        self.RB_2.clicked.connect(self.func_2)

        self.player = QMediaPlayer(None, QMediaPlayer.VideoSurface)
        self.playlist = QMediaPlaylist()

        self.player_2 = QMediaPlayer(None, QMediaPlayer.VideoSurface)
        self.playlist_2 = QMediaPlaylist()


    @pyqtSlot()

    def func_1(self):
        self.video_left()
        self.video_right()

    def func_2(self):
        self.video_left()
        self.video_right()

    def video_left(self):
        if self.RB_1.isChecked():
            self.playlist.addMedia(
                QMediaContent(QtCore.QUrl.fromLocalFile('путь к файлу №1')))
        elif self.RB_2.isChecked():
            self.playlist.addMedia(
                QMediaContent(QtCore.QUrl.fromLocalFile('путь к файлу №2')))

        self.player.setVideoOutput(self.VIDEO_widget_1)
        self.playlist.setPlaybackMode(QMediaPlaylist.CurrentItemInLoop)
        self.player.setPlaylist(self.playlist)
        self.player.play()

    def video_right(self):
        if self.RB_1.isChecked():
            self.playlist_2.addMedia(
                QMediaContent(QtCore.QUrl.fromLocalFile('путь к файлу №3')))
        elif self.RB_2.isChecked():
            self.playlist_2.addMedia(
                QMediaContent(QtCore.QUrl.fromLocalFile('путь к файлу №4')))

        self.player_2.setVideoOutput(self.VIDEO_widget_2)
        self.playlist_2.setPlaybackMode(QMediaPlaylist.CurrentItemInLoop)
        self.player_2.setPlaylist(self.playlist_2)
        self.player_2.play()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = New()
    window.show()
    sys.exit(app.exec_())

RB_Video.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Dialog</class>
 <widget class="QDialog" name="Dialog">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>1228</width>
    <height>760</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Dialog</string>
  </property>
  <widget class="QVideoWidget" name="VIDEO_widget_1" native="true">
   <property name="geometry">
    <rect>
     <x>260</x>
     <y>90</y>
     <width>300</width>
     <height>200</height>
    </rect>
   </property>
   <property name="sizePolicy">
    <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
     <horstretch>0</horstretch>
     <verstretch>0</verstretch>
    </sizepolicy>
   </property>
   <property name="minimumSize">
    <size>
     <width>300</width>
     <height>200</height>
    </size>
   </property>
   <property name="maximumSize">
    <size>
     <width>300</width>
     <height>200</height>
    </size>
   </property>
   <property name="styleSheet">
    <string notr="true">background-color: rgb(0, 0, 0);</string>
   </property>
  </widget>
  <widget class="QVideoWidget" name="VIDEO_widget_2" native="true">
   <property name="geometry">
    <rect>
     <x>610</x>
     <y>90</y>
     <width>300</width>
     <height>200</height>
    </rect>
   </property>
   <property name="sizePolicy">
    <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
     <horstretch>0</horstretch>
     <verstretch>0</verstretch>
    </sizepolicy>
   </property>
   <property name="minimumSize">
    <size>
     <width>300</width>
     <height>200</height>
    </size>
   </property>
   <property name="maximumSize">
    <size>
     <width>300</width>
     <height>200</height>
    </size>
   </property>
   <property name="styleSheet">
    <string notr="true">background-color: rgb(0, 0, 0);</string>
   </property>
  </widget>
  <widget class="QRadioButton" name="RB_1">
   <property name="geometry">
    <rect>
     <x>470</x>
     <y>390</y>
     <width>95</width>
     <height>20</height>
    </rect>
   </property>
   <property name="font">
    <font>
     <pointsize>12</pointsize>
    </font>
   </property>
   <property name="text">
    <string>RB_A</string>
   </property>
  </widget>
  <widget class="QRadioButton" name="RB_2">
   <property name="geometry">
    <rect>
     <x>630</x>
     <y>390</y>
     <width>95</width>
     <height>20</height>
    </rect>
   </property>
   <property name="font">
    <font>
     <pointsize>12</pointsize>
    </font>
   </property>
   <property name="text">
    <string>RB_B</string>
   </property>
  </widget>
 </widget>
 <customwidgets>
  <customwidget>
   <class>QVideoWidget</class>
   <extends>QWidget</extends>
   <header>PyQt5.QtMultimediaWidgets</header>
   <container>1</container>
  </customwidget>
 </customwidgets>
 <resources/>
 <connections/>
</ui>
python
  • 1 个回答
  • 10 Views
Martin Hope
Владимир
Asked: 2022-07-25 03:19:56 +0000 UTC

PyQt5 在两个单选按钮之间切换时如何使用一个拨号句柄而不是两个?

  • 1

基于此代码,我们可以radioButton_2添加另一个daL_2句柄,并通过稍微更改代码,可以根据所选的句柄对左右句柄执行算术运算radioButton。

但是如果项目中有很多这样的句柄呢?原来代码很大,窗口里有一堆。

是否可以用一支笔代替两支笔,并根据激活的一支笔获得结果radioButton?或者这样做是错误的?

主文件

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtGui import QFont
from PyQt5.QtCore import QSettings
from PyQt5.uic import loadUi

CONFIG_FILE_NAME = 'config.ini'


class New(QMainWindow):
    def __init__(self):
        super(New, self).__init__()
        loadUi("RButton_Dial_save.ui", self)

        self.Exit.clicked.connect(self.close)

        self.dial.setMinimum(0)
        self.dial.setMaximum(10)
        self.dial.setValue(5)

        self.spinbox.setRange(5, 100)
        self.spinbox.setValue(5)

        self.load_settings()

        self.dial.setMinimum(self.spinbox.value() - 5)
        self.dial.setMaximum(self.spinbox.value() + 5)
        self.dial.setValue(self.spinbox.value())
        self.dial.valueChanged.connect(self.dial_changed)

        self.spinbox.valueChanged.connect(self.spinbox_changed)

        self.statusbar = self.statusBar()
        self.statusbar.showMessage('Hello World', msecs=2000)

        self.dial.setValue(self._dial)

        self.radioButton.toggled.connect(self.rb_checked)
        self.spinbox.setEnabled(False)

    def save_settings(self):
        settings = QSettings(CONFIG_FILE_NAME, QSettings.IniFormat)
        settings.setValue('DialValue', self.dial.value())
        settings.setValue('SpinBoxValue', self.spinbox.value())

    def load_settings(self):
        settings = QSettings(CONFIG_FILE_NAME, QSettings.IniFormat)

        self.dial.setValue(
            int(settings.value('DialValue', self.spinbox.value())))
        self.spinbox.setValue(
            int(settings.value('SpinBoxValue', self.spinbox.value())))

        self._dial = int(settings.value('DialValue', self.spinbox.value()))

    def closeEvent(self, event):
        self.save_settings()

    def spinbox_changed(self, value):
        self.dial.setMinimum(value - 5)
        self.dial.setMaximum(value + 5)
        self.dial.setValue(value)

    def dial_changed(self, value):
        self.statusbar.showMessage(f'dial.value = {value}')

    def rb_checked(self, checked):
        if checked:
            self.dial.setEnabled(True)
            self.spinbox.setEnabled(True)
        else:
            self.dial.setEnabled(False)
            self.spinbox.setEnabled(False)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setFont(QFont("Times", 12, QFont.Bold))
    window = New()
    window.show()
    sys.exit(app.exec_())

RButton_Dial_save.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>800</width>
    <height>600</height>
   </rect>
  </property>
  <property name="sizePolicy">
   <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
    <horstretch>0</horstretch>
    <verstretch>0</verstretch>
   </sizepolicy>
  </property>
  <property name="maximumSize">
   <size>
    <width>800</width>
    <height>600</height>
   </size>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <property name="styleSheet">
   <string notr="true"/>
  </property>
  <widget class="QWidget" name="centralwidget">
   <property name="minimumSize">
    <size>
     <width>800</width>
     <height>600</height>
    </size>
   </property>
   <property name="maximumSize">
    <size>
     <width>800</width>
     <height>600</height>
    </size>
   </property>
   <widget class="QGroupBox" name="groupBox">
    <property name="geometry">
     <rect>
      <x>10</x>
      <y>30</y>
      <width>761</width>
      <height>211</height>
     </rect>
    </property>
    <property name="title">
     <string>GroupBox</string>
    </property>
    <widget class="QDial" name="dial">
     <property name="enabled">
      <bool>false</bool>
     </property>
     <property name="geometry">
      <rect>
       <x>200</x>
       <y>130</y>
       <width>100</width>
       <height>55</height>
      </rect>
     </property>
     <property name="wrapping">
      <bool>false</bool>
     </property>
     <property name="notchesVisible">
      <bool>true</bool>
     </property>
    </widget>
    <widget class="QPushButton" name="Exit">
     <property name="geometry">
      <rect>
       <x>650</x>
       <y>30</y>
       <width>93</width>
       <height>28</height>
      </rect>
     </property>
     <property name="text">
      <string>Выход</string>
     </property>
    </widget>
    <widget class="QSpinBox" name="spinbox">
     <property name="geometry">
      <rect>
       <x>300</x>
       <y>20</y>
       <width>111</width>
       <height>22</height>
      </rect>
     </property>
    </widget>
    <widget class="QRadioButton" name="radioButton">
     <property name="geometry">
      <rect>
       <x>230</x>
       <y>90</y>
       <width>95</width>
       <height>20</height>
      </rect>
     </property>
     <property name="text">
      <string>RButton 1</string>
     </property>
    </widget>
    <widget class="QRadioButton" name="radioButton_2">
     <property name="geometry">
      <rect>
       <x>420</x>
       <y>90</y>
       <width>95</width>
       <height>20</height>
      </rect>
     </property>
     <property name="text">
      <string>RButton 2</string>
     </property>
    </widget>
   </widget>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>
python
  • 1 个回答
  • 10 Views
Martin Hope
Владимир
Asked: 2022-07-25 01:12:13 +0000 UTC

如何在 PyQt5 中使用 radioButton 激活/停用拨号句柄?

  • 1

最初,在Qt Designer dial句柄中,我将Enabled False. 在这个任务中,句柄应该在激活时激活radioButton,在激活时停用radioButton_2。

  1. 如何在代码中实现它?
  2. 是否可以直接在Qt Designer中进行此类设置?摆脱不必要的代码编写?

主文件

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtGui import QFont
from PyQt5.QtCore import QSettings
from PyQt5.uic import loadUi

CONFIG_FILE_NAME = 'config.ini'


class New(QMainWindow):
    def __init__(self):
        super(New, self).__init__()
        loadUi("RButton_Dial_save.ui", self)

        self.Exit.clicked.connect(self.close)

        self.dial.setMinimum(0)
        self.dial.setMaximum(10)
        self.dial.setValue(5)

        self.spinbox.setRange(5, 100)
        self.spinbox.setValue(5)

        self.load_settings()

        self.dial.setMinimum(self.spinbox.value() - 5)
        self.dial.setMaximum(self.spinbox.value() + 5)
        self.dial.setValue(self.spinbox.value())
        self.dial.valueChanged.connect(self.dial_changed)

        self.spinbox.valueChanged.connect(self.spinbox_changed)

        self.statusbar = self.statusBar()
        self.statusbar.showMessage('Hello World', msecs=2000)

        self.dial.setValue(self._dial)

        self.radioButton.clicked.connect(self.spinbox_changed)

    def save_settings(self):
        settings = QSettings(CONFIG_FILE_NAME, QSettings.IniFormat)
        settings.setValue('DialValue', self.dial.value())
        settings.setValue('SpinBoxValue', self.spinbox.value())

    def load_settings(self):
        settings = QSettings(CONFIG_FILE_NAME, QSettings.IniFormat)

        self.dial.setValue(
            int(settings.value('DialValue', self.spinbox.value())))
        self.spinbox.setValue(
            int(settings.value('SpinBoxValue', self.spinbox.value())))

        self._dial = int(settings.value('DialValue', self.spinbox.value()))

    def closeEvent(self, event):
        self.save_settings()

    def spinbox_changed(self, value):
        self.dial.setEnabled(True)
        self.dial.setMinimum(value - 5)
        self.dial.setMaximum(value + 5)
        self.dial.setValue(value)

    def dial_changed(self, value):
        self.statusbar.showMessage(f'dial.value = {value}')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setFont(QFont("Times", 12, QFont.Bold))
    window = New()
    window.show()
    sys.exit(app.exec_()) 

RButton_Dial_save.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>800</width>
    <height>600</height>
   </rect>
  </property>
  <property name="sizePolicy">
   <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
    <horstretch>0</horstretch>
    <verstretch>0</verstretch>
   </sizepolicy>
  </property>
  <property name="maximumSize">
   <size>
    <width>800</width>
    <height>600</height>
   </size>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <property name="styleSheet">
   <string notr="true"/>
  </property>
  <widget class="QWidget" name="centralwidget">
   <property name="minimumSize">
    <size>
     <width>800</width>
     <height>600</height>
    </size>
   </property>
   <property name="maximumSize">
    <size>
     <width>800</width>
     <height>600</height>
    </size>
   </property>
   <widget class="QGroupBox" name="groupBox">
    <property name="geometry">
     <rect>
      <x>10</x>
      <y>30</y>
      <width>761</width>
      <height>211</height>
     </rect>
    </property>
    <property name="title">
     <string>GroupBox</string>
    </property>
    <widget class="QDial" name="dial">
     <property name="enabled">
      <bool>false</bool>
     </property>
     <property name="geometry">
      <rect>
       <x>200</x>
       <y>130</y>
       <width>100</width>
       <height>55</height>
      </rect>
     </property>
     <property name="wrapping">
      <bool>false</bool>
     </property>
     <property name="notchesVisible">
      <bool>true</bool>
     </property>
    </widget>
    <widget class="QPushButton" name="Exit">
     <property name="geometry">
      <rect>
       <x>650</x>
       <y>30</y>
       <width>93</width>
       <height>28</height>
      </rect>
     </property>
     <property name="text">
      <string>Выход</string>
     </property>
    </widget>
    <widget class="QSpinBox" name="spinbox">
     <property name="geometry">
      <rect>
       <x>300</x>
       <y>20</y>
       <width>111</width>
       <height>22</height>
      </rect>
     </property>
    </widget>
    <widget class="QRadioButton" name="radioButton">
     <property name="geometry">
      <rect>
       <x>230</x>
       <y>90</y>
       <width>95</width>
       <height>20</height>
      </rect>
     </property>
     <property name="text">
      <string>RButton 1</string>
     </property>
    </widget>
    <widget class="QRadioButton" name="radioButton_2">
     <property name="geometry">
      <rect>
       <x>420</x>
       <y>90</y>
       <width>95</width>
       <height>20</height>
      </rect>
     </property>
     <property name="text">
      <string>RButton 2</string>
     </property>
    </widget>
   </widget>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>
python
  • 1 个回答
  • 10 Views
Martin Hope
Владимир
Asked: 2022-07-24 07:57:51 +0000 UTC

如何在 PyQt5 中将 spinBox 连接到 Dial 句柄?

  • 1

输入一个spinBox数字,保存在.ini文件中。重新启动程序后,这个数字进入Dial笔的输入,操作范围从0到10。手柄的初始位置在中间,即 on5并且也保存在.ini文件中。

句柄执行算术运算。例如,我们输入100. 因此,输出应该从95到接收数字105。

如何使这个链接工作?

主文件

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.Qt import QSettings
from PyQt5.uic import loadUi

CONFIG_FILE_NAME = 'config.ini'


class New(QMainWindow):
    def __init__(self):
        super(New, self).__init__()

        loadUi("checkBox_Dial_save.ui", self)

        self.Exit.clicked.connect(self.close)

        self.dial.setMinimum(0)
        self.dial.setMaximum(10)
        self.dial.setValue(5)

        self.spinbox.setRange(1, 100)
        self.spinbox.setValue(12)

        self.load_settings()

    def save_settings(self):
        settings = QSettings(CONFIG_FILE_NAME, QSettings.IniFormat)
        settings.setValue('BoolValue', int(self.cb_flag.isChecked()))
        settings.setValue('DialValue', self.dial.value())
        settings.setValue('SpinBoxValue', self.spinbox.value())


    def load_settings(self):
        settings = QSettings(CONFIG_FILE_NAME, QSettings.IniFormat)
        self.cb_flag.setChecked(bool(int(settings.value('BoolValue', 0))))
        self.dial.setValue(int(settings.value('DialValue', 0)))
        self.spinbox.setValue(int(settings.value('SpinBoxValue', 0)))

    def closeEvent(self, event):
        self.save_settings()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = New()
    window.show()
    sys.exit(app.exec_())

checkBox_Dial_save.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>800</width>
    <height>600</height>
   </rect>
  </property>
  <property name="sizePolicy">
   <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
    <horstretch>0</horstretch>
    <verstretch>0</verstretch>
   </sizepolicy>
  </property>
  <property name="maximumSize">
   <size>
    <width>800</width>
    <height>600</height>
   </size>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <property name="styleSheet">
   <string notr="true"/>
  </property>
  <widget class="QWidget" name="centralwidget">
   <property name="minimumSize">
    <size>
     <width>800</width>
     <height>600</height>
    </size>
   </property>
   <property name="maximumSize">
    <size>
     <width>800</width>
     <height>600</height>
    </size>
   </property>
   <widget class="QGroupBox" name="groupBox">
    <property name="geometry">
     <rect>
      <x>10</x>
      <y>20</y>
      <width>761</width>
      <height>95</height>
     </rect>
    </property>
    <property name="title">
     <string>GroupBox</string>
    </property>
    <widget class="QDial" name="dial">
     <property name="geometry">
      <rect>
       <x>100</x>
       <y>28</y>
       <width>100</width>
       <height>55</height>
      </rect>
     </property>
     <property name="wrapping">
      <bool>false</bool>
     </property>
     <property name="notchesVisible">
      <bool>true</bool>
     </property>
    </widget>
    <widget class="QCheckBox" name="cb_flag">
     <property name="geometry">
      <rect>
       <x>12</x>
       <y>63</y>
       <width>81</width>
       <height>20</height>
      </rect>
     </property>
     <property name="text">
      <string>CheckBox</string>
     </property>
    </widget>
    <widget class="QPushButton" name="Exit">
     <property name="geometry">
      <rect>
       <x>650</x>
       <y>30</y>
       <width>93</width>
       <height>28</height>
      </rect>
     </property>
     <property name="text">
      <string>Выход</string>
     </property>
    </widget>
    <widget class="QSpinBox" name="spinbox">
     <property name="geometry">
      <rect>
       <x>330</x>
       <y>40</y>
       <width>111</width>
       <height>22</height>
      </rect>
     </property>
    </widget>
   </widget>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>
python
  • 1 个回答
  • 10 Views
Martin Hope
Владимир
Asked: 2022-07-23 21:33:26 +0000 UTC

PyQt5中如何在关闭程序后保存Dial句柄的位置?

  • 1

在这段代码中,我已经掌握了在按下“”按钮时将值保存checkBox在.iniВыход文件中。

代码中需要添加什么来保存调节器的位置Dial?

主文件

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.Qt import QSettings
from PyQt5.uic import loadUi

CONFIG_FILE_NAME = 'config.ini'


class New(QMainWindow):
    def __init__(self):
        super(New, self).__init__()

        loadUi("checkBox_Dial_save.ui", self)
        self.load_settings()
        self.Exit.clicked.connect(self.ExitClicked)

        self.dial.setMinimum(0)
        self.dial.setMaximum(10)
        self.dial.setValue(5)

    def save_settings(self):
        settings = QSettings(CONFIG_FILE_NAME, QSettings.IniFormat)
        settings.setValue('BoolValue', int(self.cb_flag.isChecked()))

    def load_settings(self):
        settings = QSettings(CONFIG_FILE_NAME, QSettings.IniFormat)
        self.cb_flag.setChecked(bool(int(settings.value('BoolValue', 0))))

    def ExitClicked(self):
        self.save_settings()
        sys.exit()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = New()
    window.show()
    sys.exit(app.exec_()) 

checkBox_Dial_save.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>800</width>
    <height>600</height>
   </rect>
  </property>
  <property name="sizePolicy">
   <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
    <horstretch>0</horstretch>
    <verstretch>0</verstretch>
   </sizepolicy>
  </property>
  <property name="maximumSize">
   <size>
    <width>800</width>
    <height>600</height>
   </size>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <property name="styleSheet">
   <string notr="true"/>
  </property>
  <widget class="QWidget" name="centralwidget">
   <property name="minimumSize">
    <size>
     <width>800</width>
     <height>600</height>
    </size>
   </property>
   <property name="maximumSize">
    <size>
     <width>800</width>
     <height>600</height>
    </size>
   </property>
   <widget class="QGroupBox" name="groupBox">
    <property name="geometry">
     <rect>
      <x>10</x>
      <y>20</y>
      <width>761</width>
      <height>95</height>
     </rect>
    </property>
    <property name="title">
     <string>GroupBox</string>
    </property>
    <widget class="QDial" name="dial">
     <property name="geometry">
      <rect>
       <x>100</x>
       <y>28</y>
       <width>100</width>
       <height>55</height>
      </rect>
     </property>
     <property name="wrapping">
      <bool>false</bool>
     </property>
     <property name="notchesVisible">
      <bool>true</bool>
     </property>
    </widget>
    <widget class="QCheckBox" name="cb_flag">
     <property name="geometry">
      <rect>
       <x>12</x>
       <y>63</y>
       <width>81</width>
       <height>20</height>
      </rect>
     </property>
     <property name="text">
      <string>CheckBox</string>
     </property>
    </widget>
    <widget class="QPushButton" name="Exit">
     <property name="geometry">
      <rect>
       <x>650</x>
       <y>30</y>
       <width>93</width>
       <height>28</height>
      </rect>
     </property>
     <property name="text">
      <string>Выход</string>
     </property>
    </widget>
   </widget>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>
python
  • 1 个回答
  • 10 Views
Martin Hope
Владимир
Asked: 2022-07-15 04:39:37 +0000 UTC

如何将函数绑定到 QTabWidget PyQt5 选项卡?

  • 2

此代码包含2选项卡:Tab1和Tab2,以及2函数:fun1()和fun2()。

需要添加什么,这样当你点击的时候Tab1,函数就被执行了fun1(),当你点击的时候Tab2- fun2()?

主文件

from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.uic import loadUi
import sys


class New(QMainWindow):
    def __init__(self):
        super(New, self).__init__()
        loadUi("tabs1_2.ui", self)
        self.tabWidget.currentChanged.connect(self.tabChanged)


    @pyqtSlot()
    def tabChanged(self):
        print('Позиция индекса текущей вкладки:', self.tabWidget.currentIndex())
        print('Указатель на страницу:', self.tabWidget.currentWidget())

    def fun1(self):
        print('Сработала функция 1')

    def fun2(self):
        print('Сработала функция 2')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = New()
    window.showFullScreen()
    window.tabChanged()
    sys.exit(app.exec_())

tabs1_2.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>800</width>
    <height>600</height>
   </rect>
  </property>
  <property name="sizePolicy">
   <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
    <horstretch>0</horstretch>
    <verstretch>0</verstretch>
   </sizepolicy>
  </property>
  <property name="maximumSize">
   <size>
    <width>800</width>
    <height>600</height>
   </size>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <property name="styleSheet">
   <string notr="true"/>
  </property>
  <widget class="QWidget" name="centralwidget">
   <property name="minimumSize">
    <size>
     <width>800</width>
     <height>600</height>
    </size>
   </property>
   <property name="maximumSize">
    <size>
     <width>800</width>
     <height>600</height>
    </size>
   </property>
   <widget class="QGroupBox" name="groupBox">
    <property name="geometry">
     <rect>
      <x>30</x>
      <y>10</y>
      <width>730</width>
      <height>570</height>
     </rect>
    </property>
    <property name="title">
     <string>GroupBox</string>
    </property>
    <layout class="QGridLayout" name="gridLayout">
     <item row="0" column="0">
      <widget class="QTabWidget" name="tabWidget">
       <property name="maximumSize">
        <size>
         <width>800</width>
         <height>600</height>
        </size>
       </property>
       <property name="styleSheet">
        <string notr="true">background-color: rgb(255, 255, 255);</string>
       </property>
       <property name="currentIndex">
        <number>0</number>
       </property>
       <widget class="QWidget" name="tab">
        <property name="minimumSize">
         <size>
          <width>700</width>
          <height>500</height>
         </size>
        </property>
        <property name="maximumSize">
         <size>
          <width>700</width>
          <height>500</height>
         </size>
        </property>
        <attribute name="title">
         <string>Tab 1</string>
        </attribute>
       </widget>
       <widget class="QWidget" name="tab_2">
        <property name="maximumSize">
         <size>
          <width>700</width>
          <height>500</height>
         </size>
        </property>
        <attribute name="title">
         <string>Tab 2</string>
        </attribute>
        <widget class="QWidget" name="widget_2" native="true">
         <property name="geometry">
          <rect>
           <x>11</x>
           <y>11</y>
           <width>104</width>
           <height>16</height>
          </rect>
         </property>
        </widget>
       </widget>
      </widget>
     </item>
    </layout>
   </widget>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>
python
  • 2 个回答
  • 10 Views
Martin Hope
Владимир
Asked: 2022-07-12 16:50:10 +0000 UTC

如何在 PyQt5 QtMultimedia 中随机或按顺序播放播放列表中的视频文件

  • -1

这段代码无限循环播放文件夹中的同一个文件。尽管按照计划,它应该无限循环播放文件夹中的所有内容。怎么做才对?

主文件

import sys
from PyQt5 import QtCore
from PyQt5.QtMultimedia import QMediaPlayer, QMediaPlaylist, QMediaContent
from PyQt5.QtWidgets import QDialog, QApplication
from PyQt5.uic import loadUi
import glob
import random
import os


class New(QDialog):
    def __init__(self):
        super(New, self).__init__()

        loadUi("video_form.ui", self)

        self.player = QMediaPlayer(None, QMediaPlayer.VideoSurface)
        self.playlist = QMediaPlaylist()


    def my_video(self):
        list = [1, 2]
        video_path = 'D:/путь к папке с видео'

        mmm = random.choice(list)
        for filename in glob.glob(os.path.join(video_path, f'{mmm}.mp4')):
            self.playlist.addMedia(QMediaContent(QtCore.QUrl.fromLocalFile(filename)))
            self.player.setVideoOutput(self.VIDEO_widget)
            self.playlist.setCurrentIndex(1)
            self.playlist.setPlaybackMode(QMediaPlaylist.CurrentItemInLoop)
            self.player.setPlaylist(self.playlist)
            self.player.play()


    def closeEvent(self, e):
        super().closeEvent(e)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = New()
    window.my_video()
    window.show()
    sys.exit(app.exec_())

video_form.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Dialog</class>
 <widget class="QDialog" name="Dialog">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>1024</width>
    <height>620</height>
   </rect>
  </property>
  <property name="minimumSize">
   <size>
    <width>1024</width>
    <height>620</height>
   </size>
  </property>
  <property name="maximumSize">
   <size>
    <width>1024</width>
    <height>620</height>
   </size>
  </property>
  <property name="windowTitle">
   <string>Dialog</string>
  </property>
  <property name="styleSheet">
   <string notr="true">background-color: rgb(85, 170, 255);</string>
  </property>
  <property name="sizeGripEnabled">
   <bool>false</bool>
  </property>
  <property name="modal">
   <bool>false</bool>
  </property>
  <widget class="QGroupBox" name="groupBox_7">
   <property name="geometry">
    <rect>
     <x>10</x>
     <y>10</y>
     <width>1000</width>
     <height>600</height>
    </rect>
   </property>
   <property name="minimumSize">
    <size>
     <width>1000</width>
     <height>600</height>
    </size>
   </property>
   <property name="maximumSize">
    <size>
     <width>700</width>
     <height>600</height>
    </size>
   </property>
   <property name="styleSheet">
    <string notr="true">
background-color: qlineargradient(spread:reflect, x1:0, y1:1, x2:0.492, y2:1, stop:0.0197044 rgba(0, 0, 93, 218), stop:1 rgba(255, 255, 255, 255));</string>
   </property>
   <property name="title">
    <string>ххх</string>
   </property>
   <widget class="QVideoWidget" name="VIDEO_widget" native="true">
    <property name="geometry">
     <rect>
      <x>190</x>
      <y>60</y>
      <width>640</width>
      <height>480</height>
     </rect>
    </property>
    <property name="sizePolicy">
     <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
      <horstretch>0</horstretch>
      <verstretch>0</verstretch>
     </sizepolicy>
    </property>
    <property name="minimumSize">
     <size>
      <width>640</width>
      <height>480</height>
     </size>
    </property>
    <property name="maximumSize">
     <size>
      <width>640</width>
      <height>480</height>
     </size>
    </property>
    <property name="styleSheet">
     <string notr="true">background-color: rgb(0, 0, 0);</string>
    </property>
   </widget>
  </widget>
 </widget>
 <customwidgets>
  <customwidget>
   <class>QVideoWidget</class>
   <extends>QWidget</extends>
   <header>PyQt5.QtMultimediaWidgets</header>
   <container>1</container>
  </customwidget>
 </customwidgets>
 <resources/>
 <connections/>
</ui>
pyqt5
  • 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