Qcombobox pyqt5 как получить значение
Перейти к содержимому

Qcombobox pyqt5 как получить значение

  • автор:

Получение значений из QComboBox

Учусь программировать на python, решил сделать программу и не могу понять, как мне получить новые данные из QComboBox.
На сайтах нашёл только вывод на приложение переназначенного значения QLabel.
То есть мне нужно как-то переназначить переменную CurrText.

Получение значения QComboBox
В таблице 2 столбца и не ограничееное чилсо строк, первый столбец это QComboBox. Как получить все.

Получение текста из QComboBox
Доброго форумчане! Пишу не большую программу на PyQT5, столкнулся с вопросом, как вытянуть данные .

Соответствие значений QcomboBox
Здравствуйте уважаемые программисты и форумчане. Подскажите пожалуйста, что мне необходимо добавить.

Добавление значений в QComboBox
Добрый день. у меня такая проблема, программа работает без всяких ошибок, в программе в классе.

Сообщение от zllo

Нет тот сигнал, там есть

Получение уникальных значений поля (GROUP BY) и min/max значений других полей
Доброго времени суток. Есть таблица из 4 полей: id | article | price | enabled id — уникальный.

Получение значений
Добрый день может сможете мне подсказать <form action="schet.php" method="post">.

Получение значений
Всем привет. У меня сейчас появилась такая задача, я получаю данные в таком формате: —Тут.

Получение свободных значений
Имеется таблица "servers", в ней поля "ip", "port". Нужно получить первое свободное значение поля.

Получение значений за период
Надо получить значение с начала года до &ДатаОкончания в запросе .

Drop-down selection widget

The QComboBox is a simple widget for presenting a list of options to your users in PyQt, taking up the minimum amount of screen space. The widget can have a single selected item, which is displayed in the widget area. When selected a QComboBox pops out a list of possible values from which you can select. A QComboBox can also — optionally — be made editable, so your users can enter their own values onto the list of possible values.

QComboBoxQComboBox in its closed and open state

Populating a QComboBox

Items can be added or inserted to a QComboBox , where adding appends the item to the end of the current list, while insert inserts them in a specific index in the existing list. There are convenience methods for adding multiple items to a combobox and also for adding icons to the list. The following example will demonstrate each of these using a series of comboboxes.

Run the example and compare the result with each series of add and insert steps.

Adding items to a QComboBoxAdding items to a QComboBox

You can replace the text at a specific index in the list by calling .setItemText() for example.

Finally, you can clear a QComboBox — removing all items in it — by calling .clear() .

QComboBox signals

The QComboBox emits a number of signals on state changes. When the currently selected item changes, the widget emits .currentIndexChanged() and .currentTextChanged() signals. The first receives the index of the selected entry while the second receives the text of that item. There is a further signal .activated() which is emitted for user-selections whether the index is changed or not: selecting the same entry again will still emit the signal. Highlighting an entry in the QComboBox popup list will emit the .highlighted() signal.

The following example demonstrates these signals in action.

If you run the example the signals emitted as you interact with the QComboBox will be shown in the console, giving output like that shown below. Note that when re-selecting the same entry, only the .activated() signal is emitted.

Create GUI Applications with Python & Qt6

Downloadable ebook (PDF, ePub) & Complete Source code

Purchasing Power Parity

Getting the current state

In addition to the signals, QComboBox has a few methods for getting the current state at any time. For example, you can use .currentIndex() to get the index of the currently selected item in the combobox, or use .currentText() to get the text. With the index you can also look up the text of a specific item using .itemText() . Finally, you can use .count() to get the total number of items in the combobox list.

In the example below, we use the activated signal we’ve already seen to hook up a number of methods which get information about the combobox and display this in the console. As you select any item in the combobox every method will run printing a message to the console.

Running this and selecting different items in the combobox will show the outputs.

Editable comboboxes

You can set a QComboBox to be editable allowing the user to type enter the values not currently in the list. Entered values can be added to the list, or just used as a value which is not inserted. To enable editing you can call .setEditable(True) on the widget, while control of how inserts operate is handled through the insert policy. This is set by calling .setInsertPolicy() passing one of the following flags:

Flag Value Behavior
QComboBox.NoInsert 0 No insert
QComboBox.InsertAtTop 1 Insert as first item
QComboBox.InsertAtCurrent 2 Replace currently selected item
QComboBox.InsertAtBottom 3 Insert after last item
QComboBox.InsertAfterCurrent 4 Insert after current item
QComboBox.InsertBeforeCurrent 5 Insert before current item
QComboBox.InsertAlphabetically 6 Insert in alphabetical order

For PyQt6 use the fully-qualified flag name, i.e. QComboBox.InsertPolicy.NoInsert

For example, to insert new values alphabetically, you would use.

If the combobox is set to be editable, but QComboBox.NoInsert is set as the insert policy, users will be able to enter their own custom values, but they will not be added to the list. In the following example we have two QComboBox widgets: one which is our editable box and the second which controls the insert policy of the first. Note that since the values of the flags (see above) are just numbers from 0 to 6, we can use the index to determine the flag.

If you run this example you’ll notice you can now type into the (top) editable combobox and submit them by pressing Enter. The .currentTextChanged() signal will be emitted as you type into the field.

By default the insert policy is set to QComboBox.NoInsert so entered values will not be added, just set as the value of the combobox. By selecting the insert policy in the second combobox you can change this behavior, having new entries added to the list.

Editing a QComboBox with insert policyEditing a QComboBox with insert policy

When you allow users to add values to the list, you may wish to constrain the maximum number of entries. This can be done using .setMaxCount , e.g.

For a complete guide to building GUI applications with Python, see our PyQt6 tutorial. Using another library? We also have a PyQt5 tutorial, PySide6 tutorial and PySide2 tutorial.

Never miss an update

Enjoyed this? Subscribe to get new updates straight in your Inbox.

QComboBox was written by Martin Fitzpatrick .

Martin Fitzpatrick has been developing Python/Qt apps for 8 years. Building desktop applications to make data-analysis tools more user-friendly, Python was the obvious choice. Starting with Tk, later moving to wxWidgets and finally adopting PyQt.

QComboBox was published in docs on September 05, 2021 (updated March 16, 2023 )


Inheritance diagram of PySide2.QtWidgets.QComboBox


A QComboBox provides a means of presenting a list of options to the user in a way that takes up the minimum amount of screen space.

A combobox is a selection widget that displays the current item, and can pop up a list of selectable items. A combobox may be editable, allowing the user to modify each item in the list.

Comboboxes can contain pixmaps as well as strings; the insertItem() and setItemText() functions are suitably overloaded. For editable comboboxes, the function clearEditText() is provided, to clear the displayed string without changing the combobox’s contents.

There are three signals emitted if the current item of a combobox changes, currentIndexChanged() , currentTextChanged() and activated() . currentIndexChanged() and currentTextChanged() are always emitted regardless if the change was done programmatically or by user interaction, while activated() is only emitted when the change is caused by user interaction. The highlighted() signal is emitted when the user highlights an item in the combobox popup list. All three signals exist in two versions, one with a QString argument and one with an int argument. If the user selects or highlights a pixmap, only the int signals are emitted. Whenever the text of an editable combobox is changed the editTextChanged() signal is emitted.

When the user enters a new string in an editable combobox, the widget may or may not insert it, and it can insert it in several locations. The default policy is InsertAtBottom but you can change this using setInsertPolicy() .

It is possible to constrain the input to an editable combobox using QValidator ; see setValidator() . By default, any input is accepted.

A combobox can be populated using the insert functions, insertItem() and insertItems() for example. Items can be changed with setItemText() . An item can be removed with removeItem() and all items can be removed with clear() . The text of the current item is returned by currentText() , and the text of a numbered item is returned with text(). The current item can be set with setCurrentIndex() . The number of items in the combobox is returned by count() ; the maximum number of items can be set with setMaxCount() . You can allow editing using setEditable() . For editable comboboxes you can set auto-completion using setCompleter() and whether or not the user can add duplicates is set with setDuplicatesEnabled() .

QComboBox uses the model/view framework for its popup list and to store its items. By default a QStandardItemModel stores the items and a QListView subclass displays the popuplist. You can access the model and view directly (with model() and view() ), but QComboBox also provides functions to set and get item data (e.g., setItemData() and itemText() ). You can also set a new model and view (with setModel() and setView() ). For the text and icon in the combobox label, the data in the model that has the DisplayRole and DecorationRole is used. Note that you cannot alter the SelectionMode of the view() , e.g., by using setSelectionMode() .

Constructs a combobox with the given parent , using the default model QStandardItemModel .

This enum specifies what the QComboBox should do when a new string is entered by the user.

How do I get the current text from a QcomboBox with PyQt5 using a button?

Funny that this isn’t better documented. But basically I’m just trying to get the value of a dropdown QComboBox in PyQT5 when I click a button.
Currently, when I use the following code, it is only giving me the value after I select a value in the dropdown. I am new to PyQt.

GrantRWHumphries's user avatar

3 Answers 3

I am not sure if I completely understood your question. You just want to get the text that is in the QComboBox when you click on the button? If that is the case then it’s pretty simple. First you need to get the current text in the QComboBox then put it in the QLineEdit . Your don’t need the to use a Signal here. So you can remove the following line:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *