RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

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

BrainSwitch's questions

Martin Hope
BrainSwitch
Asked: 2020-02-27 19:02:02 +0000 UTC

PyQt5 中的自定义 QGraphicsRectItem 事件

  • 1

我创建了自己的 QGraphicsRectItem,但问题是它的鼠标悬停事件方法不起作用。

编码:

import sys

from PyQt5.QtCore import Qt, QRectF
from PyQt5.QtWidgets import \
    QGraphicsScene, QGraphicsRectItem, QGraphicsView, QMainWindow, QApplication


class CustomRectItem(QGraphicsRectItem):

    def mousePressEvent(self, event):
        print('mousePressEvent')

    def mouseReleaseEvent(self, event):
        print('mouseReleaseEvent')

    def hoverMoveEvent(self, event):
        print('hoverMoveEvent')

    def hoverLeaveEvent(self, event):
        print('hoverLeaveEvent')

    def hoverEnterEvent(self, event):
        print('hoverEnterEvent')


class CustomScene(QGraphicsScene):
    def __init__(self, parent=None):
        super(CustomScene, self).__init__(QRectF(-500, -500, 500, 200), parent)
        rect = CustomRectItem()
        rect.setRect(50, 50, 50, 50)
        rect.setBrush(Qt.green)
        self.addItem(rect)


class Window(QMainWindow):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        self.scene = CustomScene(self)
        view = QGraphicsView(self.scene, self)
        view.setSceneRect(0, 0, 500, 200)
        view.setGeometry(0, 0, 600, 300)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWindow = Window()
    mainWindow.setWindowTitle('App')
    mainWindow.setGeometry(50, 50, 800, 500)
    mainWindow.show()

    sys.exit(app.exec_())
python
  • 2 个回答
  • 10 Views
Martin Hope
BrainSwitch
Asked: 2020-02-18 16:41:34 +0000 UTC

Django 数据库查询:如何通过 id 获取对象?

  • 0

Django 自动创建 id 字段作为主键。

现在我需要通过这个 id 获取一个对象。

class Person(models.Model):
    id = models.AutoField(auto_created=True, primary_key=True, verbose_name='id')
    name = models.CharField(max_length=250, verbose_name='name')
django
  • 1 个回答
  • 10 Views
Martin Hope
BrainSwitch
Asked: 2020-01-26 23:41:13 +0000 UTC

在 C++ Visual Studio 中运行服务器 [关闭]

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

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

3年前关闭。

改进问题

我启动本地 Windows 调试器 (x86)。

C++ 代码:

#include "stdafx.h"
#include <iostream>
#include <string>
#include <WS2tcpip.h>

#pragma comment(lib, "ws2_32.lib")

using namespace std;

void main()
{
    string ipAddress = "127.0.0.1";         // IP Address of the server
    int port = 54000;                       // Listening port # on the server

                                            // Initialize WinSock
    WSAData data;
    WORD ver = MAKEWORD(2, 2);
    int wsResult = WSAStartup(ver, &data);
    if (wsResult != 0)
    {
        cerr << "Can't start Winsock, Err #" << wsResult << endl;
        return;
    }

    // Create socket
    SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock == INVALID_SOCKET)
    {
        cerr << "Can't create socket, Err #" << WSAGetLastError() << endl;
        WSACleanup();
        return;
    }

    // Fill in a hint structure
    sockaddr_in hint;
    hint.sin_family = AF_INET;
    hint.sin_port = htons(port);
    inet_pton(AF_INET, ipAddress.c_str(), &hint.sin_addr);

    // Connect to server
    int connResult = connect(sock, (sockaddr*)&hint, sizeof(hint));
    if (connResult == SOCKET_ERROR)
    {
        cerr << "Can't connect to server, Err #" << WSAGetLastError() << endl;
        closesocket(sock);
        WSACleanup();
        return;
    }

    // Do-while loop to send and receive data
    char buf[4096];
    string userInput;

    do
    {
        // Prompt the user for some text
        cout << "> ";
        getline(cin, userInput);

        if (userInput.size() > 0)       // Make sure the user has typed in something
        {
            // Send the text
            int sendResult = send(sock, userInput.c_str(), userInput.size() + 1, 0);
            if (sendResult != SOCKET_ERROR)
            {
                // Wait for response
                ZeroMemory(buf, 4096);
                int bytesReceived = recv(sock, buf, 4096, 0);
                if (bytesReceived > 0)
                {
                    // Echo response to console
                    cout << "SERVER> " << string(buf, 0, bytesReceived) << endl;
                }
            }
        }

    } while (userInput.size() > 0);

    // Gracefully close down everything
    closesocket(sock);
    WSACleanup();
}

起初,应用程序没有启动。

Ошибка  LNK2019 ссылка на неразрешенный внешний символ _WinMain@16 в функции "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)
Ошибка  LNK1120 неразрешенных внешних элементов: 1      

有人告诉我我需要在项目中进行设置,即 将子系统更改为控制台。

结果,应用程序启动了,但几乎立即关闭

在调试器中:

"WindowsProject1.exe" (Win32). Загружено "C:\Users\comp\source\repos\WindowsProject1\Debug\WindowsProject1.exe". Символы загружены.
"WindowsProject1.exe" (Win32). Загружено "C:\Windows\SysWOW64\ntdll.dll". Невозможно найти или открыть PDB-файл.
"WindowsProject1.exe" (Win32). Загружено "C:\Windows\SysWOW64\kernel32.dll". Невозможно найти или открыть PDB-файл.
"WindowsProject1.exe" (Win32). Выгружено "C:\Windows\SysWOW64\kernel32.dll"
"WindowsProject1.exe" (Win32). Загружено "C:\Windows\SysWOW64\kernel32.dll". Невозможно найти или открыть PDB-файл.
"WindowsProject1.exe" (Win32). Загружено "C:\Windows\SysWOW64\KernelBase.dll". Невозможно найти или открыть PDB-файл.
"WindowsProject1.exe" (Win32). Загружено "C:\Windows\SysWOW64\ws2_32.dll". Невозможно найти или открыть PDB-файл.
"WindowsProject1.exe" (Win32). Загружено "C:\Windows\SysWOW64\sechost.dll". Невозможно найти или открыть PDB-файл.
"WindowsProject1.exe" (Win32). Загружено "C:\Windows\SysWOW64\msvcp140d.dll". Невозможно найти или открыть PDB-файл.
"WindowsProject1.exe" (Win32). Загружено "C:\Windows\SysWOW64\rpcrt4.dll". Невозможно найти или открыть PDB-файл.
"WindowsProject1.exe" (Win32). Загружено "C:\Windows\SysWOW64\sspicli.dll". Невозможно найти или открыть PDB-файл.
"WindowsProject1.exe" (Win32). Загружено "C:\Windows\SysWOW64\vcruntime140d.dll". Невозможно найти или открыть PDB-файл.
"WindowsProject1.exe" (Win32). Загружено "C:\Windows\SysWOW64\cryptbase.dll". Невозможно найти или открыть PDB-файл.
"WindowsProject1.exe" (Win32). Загружено "C:\Windows\SysWOW64\ucrtbased.dll". Невозможно найти или открыть PDB-файл.
"WindowsProject1.exe" (Win32). Загружено "C:\Windows\SysWOW64\bcryptprimitives.dll". Невозможно найти или открыть PDB-файл.
"WindowsProject1.exe" (Win32). Загружено "C:\Windows\SysWOW64\mswsock.dll". Невозможно найти или открыть PDB-файл.
"WindowsProject1.exe" (Win32). Загружено "C:\Windows\SysWOW64\kernel.appcore.dll". Невозможно найти или открыть PDB-файл.
"WindowsProject1.exe" (Win32). Загружено "C:\Windows\SysWOW64\msvcrt.dll". Невозможно найти или открыть PDB-файл.
Поток 0xb244 завершился с кодом 0 (0x0).
Поток 0x98ec завершился с кодом 0 (0x0).
Поток 0xc6ac завершился с кодом 0 (0x0).
Программа "[41160] WindowsProject1.exe" завершилась с кодом 0 (0x0).
c++
  • 1 个回答
  • 10 Views
Martin Hope
BrainSwitch
Asked: 2020-01-24 21:16:35 +0000 UTC

能够移动每个片段的图像碎片

  • 3

问题的本质在标题中,我只补充一点,用什么标签和css(甚至js,但最好没有它)并不重要,主要是图像片段可以移动。

有类似的东西,但这个解决方案不适合

javascript
  • 2 个回答
  • 10 Views
Martin Hope
BrainSwitch
Asked: 2020-01-24 15:56:52 +0000 UTC

如何在 Qt 中调整表格大小

  • 2

如何使表格不延伸到整个根小部件?

if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWindow = QWidget()
    table = QTableWidget()
    table.setGeometry(0,0,100,100)
    table.setColumnCount(2)
    table.setRowCount(3)
    table.setHorizontalHeaderLabels(['Парам.', 'Знач.'])
    parameters = ['Min', 'Max', 'Average']
    i = 0
    for p in parameters:
        table.setItem(i, 0, QTableWidgetItem(p))
        i += 1
    vbox = QVBoxLayout()
    vbox.addWidget(table)
    mainWindow.setLayout(vbox)
    mainWindow.setWindowTitle('App')
    mainWindow.setGeometry(50, 50, 1200, 800)
    mainWindow.show()

    sys.exit(app.exec_())

在图片中,一个黑框表示根小部件中的表格应该占据多大的大小。

在此处输入图像描述

python
  • 1 个回答
  • 10 Views
Martin Hope
BrainSwitch
Asked: 2020-01-14 16:08:49 +0000 UTC

PyCharm 并没有显示文件 [关闭]

  • 2
关闭。这个问题需要澄清或补充细节。目前不接受回复。

想改进这个问题?通过编辑此帖子添加更多详细信息并澄清问题。

3年前关闭。

改进问题

其实问题是如何让文件在项目中可见,比如pycache等?我确定这个文件夹(pycache)存在于项目的根目录中。

pycharm
  • 1 个回答
  • 10 Views
Martin Hope
BrainSwitch
Asked: 2020-01-11 21:07:17 +0000 UTC

React Native 上的应用

  • 0

我在文档中读到 React Native 不是 webView 而不是 html 技术。所以它不像 Elektron 应用程序,后者本质上是带有网页的可嵌入网络浏览器。

您可以判断 React Native 应用程序是否编译为本机代码。例如,如果是针对Android平台,那么转成java代码,再把java代码编译成字节码等等,如果你看技术的名字,一般情况下应该如何(在我看来)?

react-native
  • 1 个回答
  • 10 Views
Martin Hope
BrainSwitch
Asked: 2020-01-09 16:41:23 +0000 UTC

div 组件中的位置

  • 2

有一个带有任务列表的小示例。

  1. 如何使删除任务的按钮位于右侧,但位于内部div.task-view,即 最大限度地(或几乎)靠近右边界div.task-view?
  2. 如何构图div.task-view?

body{
  max-width: 300px;
  margin-left: 30%;
  margin-right: 30%;
}

li {
  list-style-type: none;
}

ul {
  padding-left: 0;
}
.task-view label{
  display: inline;
}

.remove-task {
  background: none;
  border: none;
}
<header>Todo</header>
<div class="add-task">
  <input type="text"/>
  <button>
    add task
  </button>
</div>
<ul>
  <li>
    <div class="task-view">
      <input type="checkbox"/>
      <label>One</label>
      <button class="remove-task">X</button>
    </div>
  </li>
  <li>
    <div class="task-view">
      <input type="checkbox"/>
      <label>Two</label>
      <button class="remove-task">X</button>
    </div>
  </li>
</ul>

这是一个示例的链接。

html
  • 1 个回答
  • 10 Views
Martin Hope
BrainSwitch
Asked: 2020-01-08 21:33:15 +0000 UTC

TodoMVC 应用程序

  • 0

VueJS 官方网站上有一个示例 TodoMVC 应用程序。

有人可以向我解释

  1. 双击如何更改标签以输入,因为没有“v-if”或“v-show”?

  2. 不确定样式是如何应用的?css 文件中只有一行。

.html 文件:

<section class="todoapp">
  <header class="header">
    <h1>todos</h1>
    <input class="new-todo"
      autofocus autocomplete="off"
      placeholder="What needs to be done?"
      v-model="newTodo"
      @keyup.enter="addTodo">
  </header>
  <section class="main" v-show="todos.length" v-cloak>
    <input class="toggle-all" type="checkbox" v-model="allDone">
    <ul class="todo-list">
      <li v-for="todo in filteredTodos"
        class="todo"
        :key="todo.id"
        :class="{ completed: todo.completed, editing: todo == editedTodo }">
        <div class="view">
          <input class="toggle" type="checkbox" v-model="todo.completed">
          <label @dblclick="editTodo(todo)">{{ todo.title }}</label>
          <button class="destroy" @click="removeTodo(todo)"></button>
        </div>
        <input class="edit" type="text"
          v-model="todo.title"
          v-todo-focus="todo == editedTodo"
          @blur="doneEdit(todo)"
          @keyup.enter="doneEdit(todo)"
          @keyup.esc="cancelEdit(todo)">
      </li>
    </ul>
  </section>
  <footer class="footer" v-show="todos.length" v-cloak>
    <span class="todo-count">
      <strong>{{ remaining }}</strong> {{ remaining | pluralize }} left
    </span>
    <ul class="filters">
      <li><a href="#/all" :class="{ selected: visibility == 'all' }">All</a></li>
      <li><a href="#/active" :class="{ selected: visibility == 'active' }">Active</a></li>
      <li><a href="#/completed" :class="{ selected: visibility == 'completed' }">Completed</a></li>
    </ul>
    <button class="clear-completed" @click="removeCompleted" v-show="todos.length > remaining">
      Clear completed
    </button>
  </footer>
</section>
<footer class="info">
  <p>Double-click to edit a todo</p>
  <p>Written by <a href="http://evanyou.me">Evan You</a></p>
  <p>Part of <a href="http://todomvc.com">TodoMVC</a></p>
</footer>

文件

// Full spec-compliant TodoMVC with localStorage persistence
// and hash-based routing in ~120 effective lines of JavaScript.

// localStorage persistence
var STORAGE_KEY = 'todos-vuejs-2.0'
var todoStorage = {
  fetch: function () {
    var todos = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]')
    todos.forEach(function (todo, index) {
      todo.id = index
    })
    todoStorage.uid = todos.length
    return todos
  },
  save: function (todos) {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(todos))
  }
}

// visibility filters
var filters = {
  all: function (todos) {
    return todos
  },
  active: function (todos) {
    return todos.filter(function (todo) {
      return !todo.completed
    })
  },
  completed: function (todos) {
    return todos.filter(function (todo) {
      return todo.completed
    })
  }
}

// app Vue instance
var app = new Vue({
  // app initial state
  data: {
    todos: todoStorage.fetch(),
    newTodo: '',
    editedTodo: null,
    visibility: 'all'
  },

  // watch todos change for localStorage persistence
  watch: {
    todos: {
      handler: function (todos) {
        todoStorage.save(todos)
      },
      deep: true
    }
  },

  // computed properties
  // http://vuejs.org/guide/computed.html
  computed: {
    filteredTodos: function () {
      return filters[this.visibility](this.todos)
    },
    remaining: function () {
      return filters.active(this.todos).length
    },
    allDone: {
      get: function () {
        return this.remaining === 0
      },
      set: function (value) {
        this.todos.forEach(function (todo) {
          todo.completed = value
        })
      }
    }
  },

  filters: {
    pluralize: function (n) {
      return n === 1 ? 'item' : 'items'
    }
  },

  // methods that implement data logic.
  // note there's no DOM manipulation here at all.
  methods: {
    addTodo: function () {
      var value = this.newTodo && this.newTodo.trim()
      if (!value) {
        return
      }
      this.todos.push({
        id: todoStorage.uid++,
        title: value,
        completed: false
      })
      this.newTodo = ''
    },

    removeTodo: function (todo) {
      this.todos.splice(this.todos.indexOf(todo), 1)
    },

    editTodo: function (todo) {
      this.beforeEditCache = todo.title
      this.editedTodo = todo
    },

    doneEdit: function (todo) {
      if (!this.editedTodo) {
        return
      }
      this.editedTodo = null
      todo.title = todo.title.trim()
      if (!todo.title) {
        this.removeTodo(todo)
      }
    },

    cancelEdit: function (todo) {
      this.editedTodo = null
      todo.title = this.beforeEditCache
    },

    removeCompleted: function () {
      this.todos = filters.active(this.todos)
    }
  },

  // a custom directive to wait for the DOM to be updated
  // before focusing on the input field.
  // http://vuejs.org/guide/custom-directive.html
  directives: {
    'todo-focus': function (el, binding) {
      if (binding.value) {
        el.focus()
      }
    }
  }
})

// handle routing
function onHashChange () {
  var visibility = window.location.hash.replace(/#\/?/, '')
  if (filters[visibility]) {
    app.visibility = visibility
  } else {
    window.location.hash = ''
    app.visibility = 'all'
  }
}

window.addEventListener('hashchange', onHashChange)
onHashChange()

// mount
app.$mount('.todoapp')

css 文件

[v-cloak] { display: none; }

这是此应用程序的链接。

javascript
  • 1 个回答
  • 10 Views
Martin Hope
BrainSwitch
Asked: 2020-12-21 18:53:12 +0000 UTC

转换为字符串

  • 4

有一个脚本:

def extract(filePath):

    f = open(filePath, 'rb')

    i = 0

    lines = []

    for line in f:
        print(line)
        line = str(line)
        if line == 'PlAr\n':
            break
        lines.append(line.split('\t'))

        i += 1
    return lines[13:len(lines)-1]

问题是line转换成字符串时,每行的开头都会出现字母“b”,比如在一个文件中,该行是'text',转换后变成了'b'text'' . 除了 b 字符外,还会出现引号。一般来说,如何使字符串在没有字符和引号的情况下进行转换?

python
  • 3 个回答
  • 10 Views
Martin Hope
BrainSwitch
Asked: 2020-12-20 15:41:32 +0000 UTC

使用 pip3 安装 matplotlib 包

  • 0

我在控制台中写道:

pip3 install matplotlib

以及由此产生的错误:

Collecting matplotlib
  Using cached https://files.pythonhosted.org/packages/89/0c/653aec68e9cfb775c4fbae8f71011206e5e7fe4d60fcf01ea1a9d3bc957f/matplotlib-3.0.2.tar.gz
    Complete output from command python setup.py egg_info:
    ============================================================================
    Edit setup.cfg to change the build options

    BUILDING MATPLOTLIB
                matplotlib: yes [3.0.2]
                    python: yes [3.5.2 (default, Sep 14 2017, 22:51:06)  [GCC
                            5.4.0 20160609]]
                  platform: yes [linux]

    REQUIRED DEPENDENCIES AND EXTENSIONS
                     numpy: yes [version 1.15.4]
          install_requires: yes [handled by setuptools]
                    libagg: yes [pkg-config information for 'libagg' could not
                            be found. Using local copy.]
                  freetype: no  [The C/C++ header for freetype2 (ft2build.h)
                            could not be found.  You may need to install the
                            development package.]
                       png: no  [pkg-config information for 'libpng' could not
                            be found.]
                     qhull: yes [pkg-config information for 'libqhull' could not
                            be found. Using local copy.]

    OPTIONAL SUBPACKAGES
               sample_data: yes [installing]
                  toolkits: yes [installing]
                     tests: no  [skipping due to configuration]
            toolkits_tests: no  [skipping due to configuration]

    OPTIONAL BACKEND EXTENSIONS
                       agg: yes [installing]
                     tkagg: yes [installing; run-time loading from Python Tcl /
                            Tk]
                    macosx: no  [Mac OS-X only]
                 windowing: no  [Microsoft Windows only]

    OPTIONAL PACKAGE DATA
                      dlls: no  [skipping due to configuration]

    ============================================================================
                            * The following required packages can not be built:
                            * freetype, png

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-izaasteb/matplotlib/

操作系统:linux mint

python-3.x
  • 1 个回答
  • 10 Views
Martin Hope
BrainSwitch
Asked: 2020-12-17 20:20:59 +0000 UTC

来自图形场景选定区域的项目坐标

  • 1

出于某种原因,当 print(item.x(), item.y()) 时,控制台中会显示等于 0.0 0.0 的坐标。也许坐标显示的不是相对于场景,而是相对于项目本身的坐标?

import sys
from PyQt5.QtWidgets import (QGraphicsScene, QGraphicsView,
                             QMainWindow, QApplication, QGraphicsRectItem)
from PyQt5.QtCore import QRectF, QPointF, Qt
from PyQt5.QtGui import QTransform


class GraphicsScene(QGraphicsScene):
    def __init__(self, parent=None):
        super(GraphicsScene, self).__init__(QRectF(-500, -500, 1000, 1000), parent)

        self._start = QPointF()
        self._current_rect_item = None
        self.rects = []
        k = 0
        for i in range(50):
            for j in range(50):
                self.addRect(15 * i + 10, 15 * j + 10, 10, 10)
                k += 1

    def mousePressEvent(self, event):

        clickecRect = self.itemAt(event.scenePos(), QTransform())
        if clickecRect is not None:
            clickecRect.setBrush(Qt.green)

        if self.itemAt(event.scenePos(), QTransform()) is None:
            self._current_rect_item = QGraphicsRectItem()
            self.addItem(self._current_rect_item)
            self._start = event.scenePos()
        super(GraphicsScene, self).mousePressEvent(event)

    def mouseMoveEvent(self, event):
        if self._current_rect_item is not None:
            r = QRectF(self._start, event.scenePos()).normalized()
            self._current_rect_item.setRect(r)
        super(GraphicsScene, self).mouseMoveEvent(event)
        self._start.x()
        self._start.y()
        event.scenePos().x() - self._start.x()
        event.scenePos().y() - self._start.y()
        selected_items = self.items(r)

        for rect in self.rects:
            rect.setBrush(Qt.white)

        self.rects.clear()

        selected_items = selected_items[1:]

        for item in selected_items:
            item.setBrush(Qt.green)
            self.rects.append(item)
            print(item.x(), item.y())

    def mouseReleaseEvent(self, event):
        super(GraphicsScene, self).mouseReleaseEvent(event)
        self.removeItem(self._current_rect_item)


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

        scene = GraphicsScene(self)
        view = QGraphicsView(scene, self)
        view.setSceneRect(0, 0, 1800, 2000)
        view.setGeometry(0, 0, 1200, 800)


if __name__ == '__main__':
    application = QApplication(sys.argv)
    main_window = MainWindow()
    main_window.setGeometry(100, 100, 600, 600)
    main_window.show()
    sys.exit(application.exec_())
pyqt5
  • 1 个回答
  • 10 Views
Martin Hope
BrainSwitch
Asked: 2020-11-23 14:30:11 +0000 UTC

在 QGraphicsScene 中绘制动态矩形

  • 2

在应用程序窗口中,应根据在桌面上选择东西时如何形成矩形的原理,用鼠标绘制一个矩形。

问题是矩形被绘制在错误的位置。

我还想在移动鼠标光标时更改矩形的大小,而不是mouseMoveEvent在每个事件上删除并创建一个矩形。

编码:

import sys

from PyQt5.QtWidgets import QWidget, QVBoxLayout, QGraphicsScene, QGraphicsView, QApplication


class CustomGraphicsView(QGraphicsView):
    def __init__(self, scene):
        super().__init__(scene)
        self.x = 0
        self.y = 0
        self.rect = None

    def mousePressEvent(self, QMouseEvent):
        self.x = QMouseEvent.pos().x()
        self.y =  QMouseEvent.pos().y()

    def mouseMoveEvent(self, QMouseEvent):
        new_x = QMouseEvent.pos().x()
        new_y =  QMouseEvent.pos().y()
        if self.rect != None:
            self.scene().removeItem(self.rect)
        self.rect = self.scene().addRect(self.x, self.y,  new_x - self.x, new_y - self.y)

    def mouseReleaseEvent(self, QMouseEvent):
        self.scene().removeItem(self.rect)


class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.init_UI()

    def init_UI(self):
        vbox = QVBoxLayout()
        self.setLayout(vbox)
        self.graphics_scene = QGraphicsScene(self)
        graphics_view = CustomGraphicsView(self.graphics_scene)
        vbox.addWidget(graphics_view)


if __name__ == '__main__':
    application = QApplication(sys.argv)
    main_window = MainWindow()
    main_window.setGeometry(100,100,600,600)
    main_window.show()

    sys.exit(application.exec_())
python
  • 2 个回答
  • 10 Views
Martin Hope
BrainSwitch
Asked: 2020-11-08 15:21:10 +0000 UTC

用Python中的条件将值替换为变量

  • 1

在 Javascript (EcmaScript) 中,以下表达式是可能的:

let a = 10;
let b = 20;
let result = (a === b) ? 'lala' : 'qweqwe';

当然,如果可能的话,如何在 Python(3) 中做到这一点?

javascript
  • 1 个回答
  • 10 Views
Martin Hope
BrainSwitch
Asked: 2020-11-06 16:20:31 +0000 UTC

在 PyQt5 中使用绘制的矩形数组滚动组件

  • 1

根本无法滚动。

应用代码:

import sys
from PyQt5.QtWidgets import QWidget, QApplication, QScrollArea, QVBoxLayout
from PyQt5.QtGui import QPainter, QColor


class TableComponents(QWidget):
    def __init__(self):
        self.table = []
        super().__init__()

    def paintEvent(self, QPaintEvent):
        paint = QPainter(self)
        # paint.begin(self)

        height = 20
        width = 20
        interval = 25
        i = 0
        j = 0

        while i < 100:
            while j < 100:
                paint.setBrush(QColor(50, 150, 50, 255))
                paint.drawRect(i * interval + 10, j * interval + 10, height, width)
                j += 1

            j = 0
            i += 1

class App(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        tc = TableComponents()

        scroll = QScrollArea(self)
        scroll.setGeometry(0, 0, 1400, 800)
        scroll.setWidget(tc)
        scroll.setWidgetResizable(True)

        vbox = QVBoxLayout()
        vbox.addWidget(scroll)
        self.setLayout(vbox)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWindow = App()
    mainWindow.setWindowTitle('App')
    mainWindow.setGeometry(50, 50, 1200, 800)
    mainWindow.show()

    sys.exit(app.exec_())
python
  • 1 个回答
  • 10 Views
Martin Hope
BrainSwitch
Asked: 2020-11-02 18:41:36 +0000 UTC

VueJS无法在Flask应用程序的主页上工作[重复]

  • 0
这个问题已经在这里得到了回答:
混合两个模板引擎的语法 2 个答案
3年前关闭。

Flask 和 VueJS 中有一个小应用程序,结构如下:

static
|- vue.js
templates
|- index.html
server.py

Server.py 文件内容:

from flask import Flask
from flask import render_template

app = Flask(__name__, static_folder = "static")
app.config['SECRET_KEY'] = 'secret!'

@app.route('/')
def get_main_page():
  return render_template('index.html')

if __name__ == '__main__':
 app.run()

以及 index.html 文件的内容:

<!DOCTYPE html>
<html>
<head>
 <script src="/static/vue.js"></script>
 <title>Title</title>
</head>

<body>
  <div id="app">
   {{ message }}
  </div>

  <script>
   var app = new Vue({
     el: '#app',
     data: {
      message: 'Hello Vue!'
     }
   })
  </script>
</body>
</html>

一般来说,加载网页后什么都不显示,完全是白色的。

javascript
  • 1 个回答
  • 10 Views
Martin Hope
BrainSwitch
Asked: 2020-10-30 15:52:18 +0000 UTC

使用 QGridLayout 在窗口中水平和垂直滚动

  • 4

有一个以表格形式放置组件的窗口QGridLayout。
由于使用了组件QLabel,它们可以任意数量的水平和垂直放置。
例如20 x 20,结果是400,一般情况下,会有多少组件是事先不知道的,这就是为什么需要在窗口中沿两个轴滚动的原因。

如何添加水平和垂直滚动的窗口?

这是一个示例代码:

import sys
from PyQt5.QtWidgets import QWidget, QApplication, QGridLayout, QLabel

 
class MainWindow(QWidget):
 def __init__(self):
    super().__init__()
    self.initUI()

 def initUI(self):
    self.grid = QGridLayout()
    self.setLayout(self.grid)

    self.addComponents()
    self.show()

 def addComponents(self):
    i = 0
    j = 0
    countLab = 0
    while i < 25:

        while j < 25:
            lab = QLabel('lab_'+ str(countLab))

            self.layout().addWidget(lab, i, j)
            countLab += 1
            j += 1

        j = 0
        i += 1
        

if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWindow = MainWindow()
    mainWindow.setWindowTitle('Example')
    sys.exit(app.exec_())
python
  • 1 个回答
  • 10 Views
Martin Hope
BrainSwitch
Asked: 2020-07-05 16:23:09 +0000 UTC

将一个组件的行为绑定到另一个组件的事件

  • 0

有必要在输入获得焦点时,使用 css 出现一个 div 列表。

.list {
  display: none;
}

.search:hover .list{
  display: block;
  position:absolute;
  z-index:9999;
}
<input class="search"/>

<div class="list">
  <div>one</div>
  <div>two</div>
  <div>three</div>
    
</div>

html
  • 1 个回答
  • 10 Views
Martin Hope
BrainSwitch
Asked: 2020-01-29 20:07:35 +0000 UTC

VueJS 中的变量问题

  • 0

VueJs 上有一个小型测试应用程序。问题的本质是当调用close函数的时候应该赋值this.selected_tab = 'collections',其实这并没有发生。莫名其妙。

Vue.component('collections', {
    template: "#collections",
    data: function () {
        return {
            collections: ['collection1', 'collection2', 'collection3']
        }
    }
})

var main = new Vue({
        el: "#main",
        data: {
            selected_tab: 'collections',
            tabs: ['collections'],
            lists: [
                'collection1',
                'collection2',
                'collection3'
            ]
        },
        methods: {
            showTab: function (tab) {
                this.selected_tab = tab;
            },
            selectList: function (selected) {
                console.log(selected)
                this.tabs.push(selected)
                this.selected_tab = selected;
            },
          	isActive: function (tab) {
                var result = false;
                if (this.selected_tab === tab) {
                    result = true;
                }
                return result;
            },
            close: function (index) {
                this.selected_tab = 'collections';
                this.tabs.splice(index, 1);
                console.log(this)
            }
        }
});
body {
    padding: 10px;
    font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;
}

a {
    color: #00B7FF;
}

ul.nav {
    margin-left: 0px;
    padding-left: 0px;
    list-style: none;
}

.nav li {
    float: left;
}

ul.nav a {
    display: block;
    padding: 10px;
    margin: 0 5px;
    background-color: #d4d8f4;
    border: 1px #333;
    text-decoration: none;
    color: #333;
    text-align: center;
}

ul.nav a:hover {
    background-color: #77de9a;
    color: #8f34be;
}

ul.nav a:active {
    background-color: #77de9a;
    color: #8f34be;
}

ul.nav a.active {
    background: #77de9a;
}

th.active {
    color: #fff;
}

th.active .arrow {
    opacity: 1;
}
<template id="collections">
  <div class="collections">
    <div v-for="collection in collections"><a @click.prevent="$emit('select', collection)" href="">{{ collection }}</a></div>
  </div>
</template>

<div id="main" @keyup.v="test">
  <div class="navbar navbar-inverse">
    <ul class="nav nav-tabs">
      <li v-for="key, index in tabs"><a href="" @click.prevent="showTab(key)" :class="{ active: isActive(key) }" :id="key">{{ key }}
          <button @click.prevent="close(index)" v-if="key !== 'collections'">x</button></a></li>
    </ul>
  </div>
  <collections v-if="selected_tab === 'collections'" v-on:select="selectList"></collections>
</div>

这是此应用程序的链接:https ://jsfiddle.net/pzbv3bny/

javascript
  • 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