How to Use QPushButton
Using QPushButton developers can create and handle buttons. This class is easy to use and customize so it is among the most useful classes in Qt. In general the button displays text but an icon can also be displayed.
QPushButton inherits QAbstractButton which in turn inherits QWidget .
Signals
Inherited from QAbstractButton
- void clicked(bool checked = false)
- void pressed()
- void released()
- void toggled(bool checked)
Inherited from QWidget
- void customContextMenuRequested(const QPoint &pos)
Inherited from QObject
- void destroyed(QObject *obj = nullptr)
Basic Usage
The text of QPushButton can be set upon creation or using setText(). To get the current text of the button use text().
The icon of QPushButton can also be set upon creation. After creation the icon can be changed using setIcon() To get the current icon of the button use icon()
Set Position and Size
To set the position and the size of the button use setGeometry(). If you want just to modify the size of the button use resize()
Handle Button
QPushButton emits signals if an event occurs. To handle the button connect its appropriate signal to a slot:
connect(m_button, &QPushButton::released, this, &MainWindow::handleButton);
Example
The following simple code snippet shows how to create and use QPushButton. It has been tested on Qt Symbian Simulator.
An instance of QPushButton is created. Signal released() is connected to slot handleButton() which changes the text and the size of the button.
To build and run the example:
- Create an empty folder
- Create a file for each of the below code snippets and add the example code to them (the name of the file should match the name above the snippet).
- All 4 files must be in the same folder.
- Using command line, navigate into the folder with the 4 files.
- run qmake on the project file: qmake PushButtonExample.pro
- If successful it will not print any output.
- This should create a file with the name Makefile in the folder.
- Build the application: make
- The application should compile without any issues.
- Run the application: ./PushButtonExample
The above steps are for linux but can easily be followed on other systems by replacing make with the correct make call for the system.
How to make a QPushButton disabled
I created lots of QPushButtons, added clicked signal and a slot name ´deneme()´ to all of the buttons with QT DESIGNER and the thing I want to do is; when I clicked any button, some operation should be done and lastly the button should be disabled but we do not know which button is clicked. I know I can disable the buttons with setEnabled() and isEnabled() but I do not know how to disable them.
4 Answers 4
If I understood correctly you connected various QPushButtons to the same slot. Inside of the slot deneme() you want to know which of the buttons was clicked . You can do something like:
Why is setEnabled not working then? The reference.
So a simple setEnabled(false); is enough.
If the connecting a event handler on the click event of the button maybe you should look at the QT documentation: Signal and slots
You mean Button has to be disabled right after clicking on it? I guess in that case you probably want to do something like this:
Bruno’s answer is correct.
returns a QObject* You can cast it to a QPushButton* using either C Style cast i.e QPushButton* clickedButton = (QPushButton*)(sender()) or QPushButton* clickedButton = static_cast<QPushButton*>(sender()) or QPushButton * clickedButton = qobject_cast(sender()); as far as i know qobject_cast works similar to dynamic_cast<> in C++. But if you are having compilation problems any solution given above should work fine.
-
The Overflow Blog
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.11.43304
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
QT — Как отключить кнопку
У меня есть кнопка в моей программе, которая после нажатия делает большой расчет. Я хочу отключить его в это время, когда выполняются вычисления, чтобы не допустить аварийного завершения программы, но мой метод не работал.
функция setEnabled (ложь); Я не нажму кнопку, и я могу нажать на нее столько раз, сколько захочу.
Решение
Ваши вычисления выполняются в главном потоке, поэтому ваш пользовательский интерфейс блокируется, пока вычисления не будут завершены. Пользовательский интерфейс не будет обновляться во время вычислений, и вы вернете кнопку назад в конце вычислений. Таким образом, нет никаких изменений в пользовательском интерфейсе во время вычислений.
Другие решения
Проблема с этим кодом заключается в создании цикла сообщений. При обработке одного сообщения (в данном случае это обработчик, нажимаемый кнопкой), никакие другие сообщения не обрабатываются, включая те, которые перерисовывают виджеты для отражения изменений в их состоянии. Теперь в своей функции вы отключаете кнопку и включаете ее снова, прежде чем она сможет быть обновлена.
Обратите внимание, что выполнение длинных вычислений является обработчиками сообщений пользовательского интерфейса, это плохая идея, потому что он блокирует весь пользовательский интерфейс. Вместо этого используйте асинхронную модель, такую как рабочий поток, или выполняйте вычисления поэтапно, используя таймер. Затем вы также можете увидеть отключение кнопки.