Python qt5 qlineedit get text

Получение текста из LineEdit

Есть небольшое окошко, на котором находится кнопка. По нажатию на эту кнопку создается окно, где находится 2 LineEdit, 1 CheckBox и 1 кнопка. Я пытаюсь сделать так, чтобы когда пользователь закончил ввод информации в текстовое поле вызывалась функция editCity и сохраняла информацию. Но в ней я никак не могу получить текст с этого поля, потому что нету доступа к объекту типа LineEdit

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
class Window(QMainWindow): def __init__(self): super().__init__() self.buildGUI() self.countCity = 0 self.countCom = 0 self.isAuto = False def createWidget(self): createBut = QPushButton('Create') # по нажатию создается диалог createBut.clicked.connect(self.showdialog) def showdialog(self): d = QDialog() countCityF = QLineEdit(d) countCommunF = QLineEdit(d) autoGenC = QCheckBox('Auto') ok = QPushButton("Ok", d) grid = QGridLayout() grid.setSpacing(10) grid.addWidget(QLabel('Count of the cities:', d), 1, 0) grid.addWidget(countCityF, 1, 1) grid.addWidget(QLabel('Count of communication', d), 2, 0) grid.addWidget(countCommunF, 2, 1) grid.addWidget(QLabel('Auto generate:', d), 3,0) grid.addWidget(autoGenC, 3, 1) grid.addWidget(ok, 4, 1) ok.clicked.connect(self.clickOk) autoGenC.stateChanged.connect(self.autoCheckBox) countCityF.editingFinished.connect(self.editCity) countCommunF.editingFinished.connect(self.editCom) d.setLayout(grid) d.resize(150,150) d.setWindowTitle("Setting") d.setWindowModality(Qt.ApplicationModal) d.exec_() def editCity(self): self.countCity = str(countCityF.text()) # в этой функции нужно получить текст из поля

Есть ещё команды в python для создания текста кроме команды ui.lineEdit.setText(«»)?
Я пишу свой калькулятор но при тестировании кнопок я заметил что команда ui.lineEdit.setText("Любое.

Получение строки из lineedit
Привет всем! Есть проблема: не могу получить строку вводимую в lineedit в pyqt4 main.py import.

Сохранение текста из lineEdit
Когда я пытаюсь сохранить текст из lineEdit в переменную, а потом я вывожу значение с помощью.

Как сделать кнопку неактивной, если LineEdit пустой, и активной когда в LineEdit введен текст?
Всем привет! Столкнулся с такой ситуацией: в окне есть виджет LineEdit и кнопка. Я хочу чтобы при.

Как менять цвет текста в listWidget, lineEdit итд. PyQt6, PySide6
Как можно для каждого слова отдельно применить свой цвет? Допустим items = str(‘Привет, как.

У Вас это фрагмент кода, поэтому отладчиком не проверить. Единственно, что могу сказать, у Вас в коде ошибки с отступами, а в питоне отступы это часть синтаксиса.

ЦитатаСообщение от Viktorrus Посмотреть сообщение

У Вас это фрагмент кода, поэтому отладчиком не проверить. Единственно, что могу сказать, у Вас в коде ошибки с отступами, а в питоне отступы это часть синтаксиса.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
import sys, random from PyQt5.QtWidgets import (QApplication, QWidget, QDesktopWidget, QMainWindow, QAction, qApp, QPushButton, QLabel, QTextEdit, QLineEdit, QCheckBox, QDialog, QGridLayout) from PyQt5.QtGui import QIcon, QPainter, QColor, QFont, QBrush, QImage, QPainter, QPen from PyQt5.QtCore import pyqtSlot from PyQt5.QtCore import Qt, QPointF from Graph import Top, Graph import Constant, random # здесь в скобках был QWidget class Window(QMainWindow): def __init__(self): super().__init__() self.buildGUI() self.graph = Graph() self.countCity = 0 self.countCom = 0 self.isAuto = False #self.graph = [] # our graph type - Top self.selectedTop = [] # list for two connected tops type - Top def buildGUI(self): self.resize(500,500) self.image = QImage(self.size(), QImage.Format_RGB32) self.image.fill(Qt.white) self.brushSize = 2 self.brushColor = Qt.blue self.statusBar() self.createWidget() self.center() self.setWindowTitle('Message box') self.setWindowIcon(QIcon('iconCat.png')) self.show() def mousePressEvent(self, event): if event.button() == Qt.LeftButton: # check pressing on the existing top or need to create the new top point = event.pos() # type - QPointF painter = QPainter(self.image) selected = False # typ - boolean topCur = Top(event.pos(), self.graph.size()+1) # type - Top for top in self.graph.getSetV(): if top.inside(point): self.brushColor = Qt.red # selected selected = True topCur = top if top in self.selectedTop: self.brushColor = Qt.blue self.selectedTop.remove(top) else: self.selectedTop.append(top) # add in selected list break if not selected: # create the top of the graph and installed of the color pen self.brushColor = Qt.blue self.graph.add(topCur) #self.graph.append(topCur) painter.drawText(point, str(topCur.getNumber())) self.pen(painter) painter.drawEllipse(topCur.x()-Constant.rad/2, topCur.y()-Constant.rad/2, Constant.rad, Constant.rad) # create the line if len(self.selectedTop) == 2: self.brushColor = Qt.green self.pen(painter) top1 = self.selectedTop.pop(1) # type - Top top2 = self.selectedTop.pop(0) # check for excisting the road if not top1.exsitRoad(top2): painter.drawLine(top1.x(), top1.y(), top2.x(), top2.y()) # target - add first top (top1) connected top (top2) in the list # bilaterial weight = random.randint(1, 20) price = random.randint(25, 100) top1.add(top2, weight, price) top2.add(top1, weight, price) # for title the wight over of the line posWight = QPointF((top1.x() + top2.x()) / 2 + 5, (top1.y() + top2.y()) / 2 - 5) self.brushColor = Qt.black self.pen(painter) painter.drawText(posWight, "w=" + str(weight)) painter.drawText(QPointF((top1.x() + top2.x()) / 2 + 5, (top1.y() + top2.y()) / 2 + 15), "p=" + str(price)) self.brushColor = Qt.blue; self.pen(painter) painter.drawEllipse(top1.x() - Constant.rad/2, top1.y() - Constant.rad/2, Constant.rad, Constant.rad) painter.drawEllipse(top2.x() - Constant.rad/2, top2.y() - Constant.rad/2, Constant.rad, Constant.rad) self.update() def paintEvent(self, event): canvasPainter = QPainter(self) canvasPainter.drawImage(self.rect(), self.image, self.image.rect()) def pen(self, painter): painter.setPen( QPen(self.brushColor, self.brushSize, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) # installed the pen def createWidget(self): exitAction = QAction(QIcon('iconCat.png'), '&Exit', self) # create action, install icon, text and parent(where it is) exitAction.setShortcut('Ctrl+Q') # hot keys exitAction.setStatusTip('Exit application') # tip exitAction.triggered.connect(qApp.quit) self.toolbar = self.addToolBar('Exit') self.toolbar.addAction(exitAction) createBut = QPushButton('Create') runBut = QPushButton('Run') # graph is generated, find the path createBut.clicked.connect(self.on_click) runBut.clicked.connect(self.click_run) # start the work of the basic target program toolbar = self.addToolBar('Exit') toolbar.addWidget(createBut) toolbar.addWidget(runBut) @pyqtSlot() def on_click(self): self.showdialog() # for top in self.graph.getSetV(): # top.info() @pyqtSlot() def click_run(self): self.graph.deystra(1) self.graph.printPath(4) # сделать ввод @pyqtSlot() def clickOk(self): # random if self.isAuto: print('g') else: print('fff') def autoCheckBox(self, state): if state == Qt.Checked: self.isAuto = True else: self.isAuto = False # ошибка def editCity(self): self.countCity = str(countCityF.text()) def editCom(self): self.countCom = str(countCommunF.text()) def center(self): position = self.frameGeometry() #get rectangle our app cnrScreen = QDesktopWidget().availableGeometry().center() # get the center point on the screen position.moveCenter(cnrScreen) # rect put on the center self.move(position.topLeft()) # shift app def showdialog(self): d = QDialog() countCityF = QLineEdit(d) countCommunF = QLineEdit(d) autoGenC = QCheckBox('Auto') ok = QPushButton("Ok", d) grid = QGridLayout() grid.setSpacing(10) grid.addWidget(QLabel('Count of the cities:', d), 1, 0) grid.addWidget(countCityF, 1, 1) grid.addWidget(QLabel('Count of communication', d), 2, 0) grid.addWidget(countCommunF, 2, 1) grid.addWidget(QLabel('Auto generate:', d), 3,0) grid.addWidget(autoGenC, 3, 1) grid.addWidget(ok, 4, 1) ok.clicked.connect(self.clickOk) autoGenC.stateChanged.connect(self.autoCheckBox) countCityF.editingFinished.connect(self.editCity) countCommunF.editingFinished.connect(self.editCom) d.setLayout(grid) d.resize(150,150) d.setWindowTitle("Setting") d.setWindowModality(Qt.ApplicationModal) d.exec_() if __name__ == '__main__': app = QApplication(sys.argv) ex = Window() sys.exit(app.exec_())

Источник

Читайте также:  Writing mode in python

PyQt QLineEdit

Every GUI needs a way of taking input from the User. In PyQt, the most common way of taking input is through the QLineEdit widget. It offers you a single line where you can input Text.

If you wish for a way to get Multi-Line Text input, you will have to use the QTextEdit widget instead.

You will find a complete list of functions and options available for the QLineEdit here in this article.

Creating a QLineEdit Widget

Below is the simplest implementation of the QLineEdit Widget.

The QtWidgets.QLineEdit() function is used to create a QLineEdit() widget by passing as parameter the window obect we created earlier.

from PyQt5 import QtWidgets from PyQt5.QtWidgets import QApplication, QMainWindow import sys def show(): print(line.text()) app = QApplication(sys.argv) win = QMainWindow() win.setGeometry(400,400,300,300) win.setWindowTitle("CodersLegacy") line = QtWidgets.QLineEdit(win) line.move(100,80) win.show() sys.exit(app.exec_())

QLineWidget PyQt - Base

In it’s base form, QLineEdit is very plain and simple. However there are over a dozen different methods that can be used to enhance it’s functionality as you’ll see below.

All examples after this well have the imports and setup code for the PyQt removed to decrease the amount of repeated code.

Retrieving QLineEdit values

In order to retrieve the entered text from the QLineEdit widget, you have to use the text() method on it. There are many different ways to use this method, either with the use of QLineEdit ‘s inbuilt functions or another widget.

In this example we’ll be using the QPushButton widget. We’ve created a submit button that calls the function show that uses the text() method on our QLineEdit object.

def show(): print(line.text()) line = QtWidgets.QLineEdit(win) line.move(100,80) button = QtWidgets.QPushButton(win) button.setText("Submit") button.clicked.connect(show) button.move(100,150) button = QtWidgets.QPushButton(win) button.setText("Clear") button.clicked.connect(line.clear) button.move(100,220) win.show() sys.exit(app.exec_())

We’ve also thrown in a bonus Clear button that calls the clear() method on the QLineEdit widget. This deletes all the contents of the QLineEdit widget.

Читайте также:  Python if name exists

QLineEdit - Retrieve values

Try the code for the PyQt5 QLineEdit widget yourself to understand more.

Other QLineEdit Methods

Here are few additional code examples that cover the most important and useful QLineEdit features.

Taking passwords from User

The setEchoMode() takes several different “modes”, one of which is the password mode. This obscures the password and protects it from unwanted eyes.

def show(): print(line.text()) line = QtWidgets.QLineEdit(win) line.setEchoMode(QtWidgets.QLineEdit.Password) line.move(100,80) button = QtWidgets.QPushButton(win) button.setText("Submit") button.clicked.connect(show) button.move(100,150) win.show() sys.exit(app.exec_())

QLineEdit - password

Changing widget size

Using the setFixedWidth() method we can change the size of the QLineEdit() widget in terms of pixels.

def show(): print(line.text()) app = QApplication(sys.argv) win = QMainWindow() win.setGeometry(400,400,300,300) win.setWindowTitle("CodersLegacy") line = QtWidgets.QLineEdit(win) line.setFixedWidth(140) line.move(80,80) win.show() sys.exit(app.exec_())

Compare the size of this one to the one shown in the start of this article. The default value of each widget is around 100 pixels.

QLineEdit Methods

QLineEdit Signals

This marks the end of the PyQt QLineEdit article. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the article content can be asked in the comments section below.

Источник

Оцените статью